简体   繁体   English

Pythonic 打印列表项的方法

[英]Pythonic way to print list items

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 ?如果我们可以用综合列表来做这种事情,为什么不作为一个列表之外的简单语句呢?

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.正如 mgilson 在评论中指出的那样,您可以使用from __future__ import print_function在 Python 2.x 上获得相同的行为。

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:使用 Python 2.x 上的 print 语句,您将需要某种迭代,关于您关于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) 

I use this all the time :我经常用这个 :

#!/usr/bin/python

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

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

For Python 2.*:对于 Python 2.*:

If you overload the function __str__() for your Person class, you can omit the part with map(str, ...).如果为 Person 类重载函数 __str__(),则可以省略带有 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.在 Python 3.* 中有 print() 函数的参数sep Take a look at documentation.看看文档。

Expanding @lucasg's answer (inspired by the comment it received):扩展@lucasg 的答案(受到它收到的评论的启发):

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

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.希望我有所帮助。

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.简单易读,可与格式字符串一起使用。

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 非常陌生,我敢肯定这对专家来说很笨拙,但我只是在这里举个例子

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

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 exist which is:答案是,它确实存在,即:

[p for p in myList] #works perfectly

Basically, use [] for list comprehension and get rid of print to avoiding printing None .基本上,使用[]进行列表理解并摆脱print以避免打印None To see why print prints None see this要了解为什么print打印None ,请参阅

使用单行代码打印给定列表的每个元素

 for i in result: print(i)

You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:您还可以使用 len() 函数并确定列表的长度以打印元素,如下例所示:

sample_list = ['Python', 'is', 'Easy']

for i in range(0, len(sample_list)):

      print(sample_list[i])

Reference : https://favtutor.com/blogs/print-list-python参考: https ://favtutor.com/blogs/print-list-python

you can try doing this: this will also print it as a string您可以尝试这样做:这也会将其打印为字符串

print(''.join([p for p in myList]))

or if you want to a make it print a newline every time it prints something或者如果你想让它每次打印一些东西时都打印一个换行符

print(''.join([p+'\n' for p in myList]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM