Python:for 循环内的 print()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20774607/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:12:27  来源:igfitidea点击:

Python: for loop inside print()

pythonlistpython-3.xprinting

提问by SomeOne

I have a question about Python (3.3.2).

我有一个关于 Python (3.3.2) 的问题。

I have a list:

我有一个清单:

L = [['some'], ['lists'], ['here']] 

I want to print these nested lists (each one on a new line) using the print()function:

我想使用以下print()函数打印这些嵌套列表(每个列表都在一个新行上):

print('The lists are:', for list in L: print(list, '\n'))

I know this is incorrect but I hope you get the idea. Could you please tell me if this is possible? If yes, how?

我知道这是不正确的,但我希望你能明白。你能告诉我这是否可能吗?如果是,如何?

I know that I could do this:

我知道我可以这样做:

for list in L:
    print(list)

However, I'd like to know if there are other options as well.

但是,我想知道是否还有其他选择。

采纳答案by Martijn Pieters

Apply the whole Lobject as separate arguments:

将整个L对象作为单独的参数应用:

print('The lists are:', *L, sep='\n')

By setting septo a newline this'll print all list objects on new lines.

通过设置sep换行符,这将在新行上打印所有列表对象。

Demo:

演示:

>>> L = [['some'], ['lists'], ['here']]
>>> print('The lists are:', *L, sep='\n')
The lists are:
['some']
['lists']
['here']

If you haveto use a loop, do so in a list comprehension:

如果必须使用循环,请在列表推导式中使用:

print('The lists are:', '\n'.join([str(lst) for lst in L]))

This'll omit the newline after 'The lists are:', you can always use sep='\n'here as well.

这将省略 之后的换行符'The lists are:',您也可以随时sep='\n'在此处使用。

Demo:

演示:

>>> print('The lists are:', '\n'.join([str(lst) for lst in L]))
The lists are: ['some']
['lists']
['here']
>>> print('The lists are:', '\n'.join([str(lst) for lst in L]), sep='\n')
The lists are:
['some']
['lists']
['here']

回答by SomeOne

This works:

这有效:

>>> L = [['some'], ['lists'], ['here']]
>>> print("\n".join([str(x) for x in L]))
['some']
['lists']
['here']
>>>

回答by Nurul Akter Towhid

work for me:

为我工作:

L = [['some'], ['lists'], ['here']]
print("\n".join('%s'%item for item in L))

this one also work:

这个也有效:

L = [['some'], ['lists'], ['here']]
print("\n".join(str(item) for item in L))

this one also:

这也是:

L = [['some'], ['lists'], ['here']]
print("\n".join([str(item) for item in L]))

回答by user8892564

If anyone looking for help in dict printing then here u go:

如果有人在 dict 打印方面寻求帮助,那么你就在这里:

dictionary = {'test1':'value1', 'test1':'value1'}


print ('\n'.join(' : '.join(b for b in a) for a in dictionary.items()))