Python 逐行打印列表元素 - 是否可以使用格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22695171/
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
print list elements line by line - is it possible using format
提问by andilabs
I very like quite new Python convention to print things with .format()
我非常喜欢用新的 Python 约定来打印东西 .format()
Is it possible using it to print element line by line. Assuming of course number of elements is unknown.
是否可以使用它逐行打印元素。当然,假设元素的数量是未知的。
Working example will be appreciated.
工作示例将不胜感激。
采纳答案by poke
You can use the string formatter on really any kind of string, including multi-line string. So of course, if you had a format string '{}\n{}\n{}'you could pass three items to it, and they would be all placed on separate lines.
您可以在任何类型的字符串上使用字符串格式化程序,包括多行字符串。所以当然,如果你有一个格式字符串,'{}\n{}\n{}'你可以向它传递三个项目,它们都将放在不同的行上。
So with a dynamic number of elements you want to print, all you need to do is make sure that the format string contains the same number of format items too. One way to solve this would be to construct the format string dynamically. For example this:
因此,对于您想要打印的动态数量的元素,您需要做的就是确保格式字符串也包含相同数量的格式项。解决此问题的一种方法是动态构造格式字符串。例如这个:
'\n'.join('{}' for _ in range(len(my_list))).format(*my_list)
So you essentially create a format string first, by having a generator produce one format item {}per element in my_list, and joining these using a newline character. So the resulting string looks something like this: {}\n{}\n…\n{}\n{}.
因此,您实际上首先创建了一个格式字符串,方法是让生成器{}为 中的每个元素生成一个格式项my_list,并使用换行符将这些项连接起来。所以生成的字符串看起来是这样的:{}\n{}\n…\n{}\n{}。
And then you use that string as the format string, and call formaton it, passing the unpacked list as arguments to it. So you are correctly filling all spots of the format string.
然后您使用该字符串作为格式字符串,并调用format它,将解压缩的列表作为参数传递给它。因此,您正确填充了格式字符串的所有位置。
So, you cando it. However, this is not really a practical idea. It looks rather confusing and does not convey your intention well. A better way would be to handle each item of your list separately and format it separately, and only thenjoin them together:
所以,你可以做到。然而,这并不是一个实际的想法。它看起来相当混乱,并不能很好地传达您的意图。更好的方法是分别处理列表中的每个项目并分别格式化,然后才将它们连接在一起:
'\n'.join('{}'.format(item) for item in my_list)
As for just printing elements line by line, of course, the more obvious way, that wouldn't require you to build one long string with line breaks, would be to loop over the items and just print them one-by-one:
至于仅逐行打印元素,当然,更明显的方法是不需要您构建一个带换行符的长字符串,而是遍历项目并逐个打印它们:
for item in my_list:
print(item)
# or use string formatting for the item here
print('{}'.format(item))
And of course, as thefourtheye suggested, if each loop iteration is very simple, you can also pass the whole list to the print function, and set sep='\n'to print the elements on separate lines each.
当然,正如thefourtheye 所建议的,如果每次循环迭代都非常简单,您也可以将整个列表传递给print 函数,并设置sep='\n'为在每个单独的行上打印元素。
回答by kojiro
You mean like print('\n'.join(a_list))? String formatting could probably do something similar to '\n'.join(a_list), but it doesn't seem necessary here. (see update)
你是说喜欢print('\n'.join(a_list))?字符串格式可能会做类似于 的事情'\n'.join(a_list),但在这里似乎没有必要。(见更新)
The thing is, .formatdoesn't print things at all. That's what printis for. formattakes some data and returns a string. printis one way to output that string to the terminal/standard output, but printand .formatdon't really have any real relationship.
问题是,.format根本不打印东西。这print就是为了。format获取一些数据并返回一个字符串。print是将该字符串输出到终端/标准输出的一种方法,但实际上print并.format没有任何实际关系。
Update:
更新:
I take back what I said about string formatting being able to do this. The format pattern itself predefines the arityof the formatmethod, so short of dynamically building the format pattern, you can't use formatfor this.
我收回我所说的字符串格式能够做到这一点。格式模式本身的预定义元数的的format方法,这么短的动态构建格式模式,则不能使用format此。
回答by thefourtheye
If you are using Python 3.x and your intention is to just printing the list of elements, one in each line, then you can use printfunction itself, like this
如果您使用的是 Python 3.x 并且您的目的只是打印元素列表,每行一个,那么您可以使用print函数本身,如下所示
my_list = [1, 2, 3, 4]
print(*my_list, sep="\n")
*my_listsimply unpacks the list elements and pass each one of them as parameters to the printfunction (Yes, printis a function in Python 3.x).
*my_list只需解压缩列表元素并将它们中的每一个作为参数传递给print函数(是的,print是 Python 3.x 中的函数)。
Output
输出
1
2
3
4
If you are using Python 2.x, then you can just import the print function from the future like this
如果您使用的是 Python 2.x,那么您可以像这样从未来导入打印功能
from __future__ import print_function
Note:This import should be the first line in the file.
注意:此导入应该是文件中的第一行。
回答by kiriloff
Keep It Simple
把事情简单化
>>> myList = [2,3,5,6,5,4,3,2]
>>> for elem in myList:
'{}'.format(elem)
gives
给
'2'
'3'
'5'
'6'
'5'
'4'
'3'
'2'
Is it what you wish obtain?
是你希望得到的吗?
回答by kamyonet
Another way to do it is to use string multiplication:
另一种方法是使用字符串乘法:
my_list = [1, 2, 3, 4, 5]
print(('{}\n'*len(my_list)).format(*my_list))
For plain old printing, I'd use the sep option of the print command. The format method is more useful if you are using the python logging facilities (which do not have the sep argument).
对于普通的旧打印,我会使用打印命令的 sep 选项。如果您使用 python 日志记录工具(没有 sep 参数),则 format 方法更有用。
回答by Adarsh Pawar
We can use jointo print line by line:
我们可以使用join逐行打印:
>>> x = ['a','b','c']
>>> print("\n".join(x))
a
b
c
回答by andilabs
one more idea to get the string not needing to print it:
获得不需要打印的字符串的另一个想法:
my_list = [1, 2, 3, 4]
str("{}\n"*len(my_list)).format(*my_list)

