打印列表项的 Pythonic 方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15769246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pythonic way to print list items
提问by Guillaume Vtheitroadon
I would like to know if there is a better way to print all objects in a Python list than this :
我想知道是否有比这更好的方法来打印 Python 列表中的所有对象:
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
我这样读并不是很好:
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
是不是有类似的东西:
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 ?
如果没有,我的问题是......为什么?如果我们可以用综合列表来做这种事情,为什么不作为列表之外的简单语句呢?
采纳答案by Andrew Clark
Assuming you are using Python 3.x:
假设您使用的是 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.
您可以在 Python 2.x 上使用 获得相同的行为from __future__ import print_function,如 mgilson 在评论中所述。
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myListnot working, you can just use the following which does the same thing and is still one line:
使用 Python 2.x 上的打印语句,您将需要某种类型的迭代,关于您关于print(p) for p in myList不工作的问题,您可以使用以下执行相同操作并且仍然是一行的内容:
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:
对于使用 的解决方案'\n'.join(),我更喜欢列表推导式和生成器,map()因此我可能会使用以下内容:
print '\n'.join(str(p) for p in myList)
回答by lucasg
I use this all the time :
我经常用这个 :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
回答by gukoff
For Python 2.*:
对于 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:
如果为 Person 类重载函数 __str__(),则可以使用 map(str, ...) 省略部分。另一种方法是创建一个函数,就像你写的:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sepfor the print() function. Take a look at documentation.
在 Python 3.*中有 print() 函数的参数sep。看看文档。
回答by ytpillai
[print(a) for a in list]will give a bunch of None types at the end though it prints out all the items
[print(a) for a in list]尽管它会打印出所有项目,但最后会给出一堆 None 类型
回答by Floris
Expanding @lucasg's answer (inspired by the comment it received):
扩展@lucasg 的答案(受到它收到的评论的启发):
To get a formattedlist output, you can do something along these lines:
要获得格式化的列表输出,您可以执行以下操作:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", "provides the separator (only between items, not at the end) and the formatting string '02d'combined with %xgives a formatted string for each item x- in this case, formatted as an integer with two digits, left-filled with zeros.
现在", "提供分隔符(仅在项目之间,而不是在末尾)和格式化字符串'02d'结合%x为每个项目提供格式化字符串x- 在这种情况下,格式化为两位数的整数,左填充零。
回答by ShinyMemes
To display each content, I use:
为了显示每个内容,我使用:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
在函数中使用的示例:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
希望我有所帮助。
回答by Rongzhao Zhang
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.
简单易读,可与格式字符串一起使用。
回答by Aethalides
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
假设您可以打印列表 [1,2,3],那么 Python3 中的一个简单方法是:
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']
这个lorem列表中有8个项目:[1, 2, 3, 'lorem', 'ipsum', 'dolor', 'sit', 'amet']
回答by Gaurav Singhal
OP's question is: does something like following exists, if not then why
OP的问题是:是否存在以下内容,如果不存在,那么为什么
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does existwhich is:
答案是,它确实存在,即:
[p for p in myList] #works perfectly
Basically, use []for list comprehension and get rid of printto avoiding printing None. To see why printprints Nonesee this
基本上,[]用于列表理解并摆脱print避免打印None。要了解为什么print打印会None看到这个
回答by Nate Baker
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
我最近制作了一个密码生成器,虽然我对 python 非常陌生,但我还是把它作为一种在列表中显示所有项目的方式(稍作修改以满足您的需求......
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
就像我说的,我对 Python 非常陌生,我相信这对于专家来说很笨拙,但我只是在这里举另一个例子

