打印列表项的 Pythonic 方式 [英] 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("
".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='
')
您可以使用 from __future__ import print_function
在 Python 2.x 上获得相同的行为,如 mgilson 在评论中所述.
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(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
对于使用 '
'.join()
的解决方案,我更喜欢列表推导式和生成器而不是 map()
,所以我可能会使用以下内容:
For a solution that uses '
'.join()
, I prefer list comprehensions and generators over map()
so I would probably use the following:
print '
'.join(str(p) for p in myList)
这篇关于打印列表项的 Pythonic 方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!