Pythonic way to print list items

后端 未结 11 1007
渐次进展
渐次进展 2020-11-22 10:29

I would like to know if there is a better way to print all objects in a Python list than this :

myList = [Person(\"Foo\"), Person(\"Bar\")]
print(\"\\n\".joi         


        
相关标签:
11条回答
  • 2020-11-22 11:15

    For Python 2.*:

    If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:

    def write_list(lst):
        for item in lst:
            print str(item) 
    
    ...
    
    write_list(MyList)
    

    There is in Python 3.* the argument sep for the print() function. Take a look at documentation.

    0 讨论(0)
  • 2020-11-22 11:16

    I think this is the most convenient if you just want to see the content in the list:

    myList = ['foo', 'bar']
    print('myList is %s' % str(myList))
    

    Simple, easy to read and can be used together with format string.

    0 讨论(0)
  • 2020-11-22 11:19

    Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:

    mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
    
    print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
    

    Running this produces the following output:

    There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum', 'dolor', 'sit', 'amet']

    0 讨论(0)
  • 2020-11-22 11:22

    To print each element of a given list using a single line code

     for i in result: print(i)
    
    0 讨论(0)
  • 2020-11-22 11:26

    [print(a) for a in list] will give a bunch of None types at the end though it prints out all the items

    0 讨论(0)
提交回复
热议问题