用Python方式打印列表项 [英] Pythonic way to print list items
问题描述
我想知道是否有比这更好的方法来打印Python列表中的所有对象:
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".join(map(str, myList)))
Foo
Bar
我这样读不是很好:
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
没有类似的东西:
print(p) for p in myList
如果没有,我的问题是...为什么?如果我们可以使用综合列表来完成这类工作,为什么不将其作为列表之外的简单语句呢?
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
推荐答案
假设您使用的是Python 3.x:
Assuming you are using Python 3.x:
print(*myList, sep='\n')
mgilson在注释中指出,您可以使用from __future__ import print_function
在Python 2.x上获得相同的行为.
You can get the same behavior on Python 2.x using from __future__ import print_function
, as noted by mgilson in comments.
使用Python 2.x上的print语句,您需要某种形式的迭代,关于您关于print(p) for p in myList
无效的问题,您可以使用以下代码做同样的事情,并且仍然是一行:
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
对于使用'\n'.join()
的解决方案,相对于map()
,我更喜欢列表推导和生成器,因此我可能会使用以下内容:
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)
这篇关于用Python方式打印列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!