问题:Python方式打印列表项

我想知道是否有比这更好的方法来打印Python列表中的所有对象:

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

如果没有,我的问题是…为什么?如果我们可以使用综合列表来完成此类工作,为什么不将其作为列表之外的简单语句呢?

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

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 ?


回答 0

假设您正在使用Python 3.x:

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

您可以使用from __future__ import print_function,在Python 2.x上获得相同的行为,如mgilson在评论中所述。

使用Python 2.x上的print语句,您将需要某种形式的迭代,关于您的print(p) for p in myList不工作问题,您可以使用以下代码做同样的事情,并且仍然是一行:

for p in myList: print p

对于使用的解决方案'\n'.join(),我更喜欢列表推导和生成器,map()因此我可能会使用以下内容:

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

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) 

回答 1

我经常用这个 :

#!/usr/bin/python

l = [1,2,3,7] 
print "".join([str(x) for x in l])

I use this all the time :

#!/usr/bin/python

l = [1,2,3,7] 
print "".join([str(x) for x in l])

回答 2

[print(a) for a in list] 尽管会打印出所有项目,但最后会给出一堆None类型

[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items


回答 3

对于Python 2. *:

如果为您的Person类重载了函数__str __(),则可以省略带有map(str,…)的部分。另一种方法是创建一个函数,就像您写的那样:

def write_list(lst):
    for item in lst:
        print str(item) 

...

write_list(MyList)

Python 3. * 中有print()函数的参数sep。看一下文档。

For 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:

def write_list(lst):
    for item in lst:
        print str(item) 

...

write_list(MyList)

There is in Python 3.* the argument sep for the print() function. Take a look at documentation.


回答 4

扩展@lucasg的答案(受其收到的评论启发):

要获得格式化的列表输出,可以按照以下步骤进行操作:

l = [1,2,5]
print ", ".join('%02d'%x for x in l)

01, 02, 05

现在,", "提供分隔符(仅在项目之间,而不是末尾),并且'02d'结合使用%x格式字符串为每个项目提供格式化的字符串x-在这种情况下,格式为具有两位数字的整数,并用零填充。

Expanding @lucasg’s answer (inspired by the comment it received):

To get a formatted list 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 %x gives a formatted string for each item x – in this case, formatted as an integer with two digits, left-filled with zeros.


回答 5

要显示每个内容,我使用:

mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):     
    print(mylist[indexval])
    indexval += 1

在函数中使用的示例:

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.')

希望我能帮上忙。

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.


回答 6

我认为如果您只想查看列表中的内容,这是最方便的:

myList = ['foo', 'bar']
print('myList is %s' % str(myList))

简单,易读,可与格式字符串一起使用。

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.


回答 7

OP的问题是:是否存在类似以下内容的内容,如果不存在,为什么?

print(p) for p in myList # doesn't work, OP's intuition

答案是,它确实存在,它是:

[p for p in myList] #works perfectly

基本上,[]用于列表理解并print避免避免打印None。看看为什么print打印None看到这个

OP’s question is: does something like following exists, if not then why

print(p) for p in myList # doesn't work, OP's intuition

answer is, it does exist which is:

[p for p in myList] #works perfectly

Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this


回答 8

我最近制作了一个密码生成器,尽管我对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)

就像我说的,IM对Python非常新,我相信这对于专家来说是笨拙的方式,但是我在这里只是另一个例子

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…

    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


回答 9

假设您可以很好地打印列表[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}")

运行此命令将产生以下输出:

此lorem列表中有8个项目:[1、2、3,’lorem’,’ipsum’,’dolor’,’sit’,’amet’]

Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:

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’]


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。