Pythonic way to print list items

后端 未结 11 1118
渐次进展
渐次进展 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:05

    Assuming you are using Python 3.x:

    print(*myList, sep='\n')
    

    You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.

    With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:

    for p in myList: print p
    

    For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:

    print '\n'.join(str(p) for p in myList) 
    

提交回复
热议问题