且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用Python方式打印列表项

更新时间:2023-12-05 15:09:16

假设您使用的是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)