Python:for循环内部print()

Som*_*One 8 python printing list python-3.x

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

我有一个清单:

L = [['some'], ['lists'], ['here']] 
Run Code Online (Sandbox Code Playgroud)

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

print('The lists are:', for list in L: print(list, '\n'))
Run Code Online (Sandbox Code Playgroud)

我知道这是不正确的,但我希望你明白这个想法.你能告诉我这是否可行?如果有,怎么样?

我知道我可以这样做:

for list in L:
    print(list)
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 20

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

print('The lists are:', *L, sep='\n')
Run Code Online (Sandbox Code Playgroud)

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

演示:

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

如果必须使用循环,请在列表推导中执行此操作:

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

这将省略换行后'The lists are:',你也可以随时使用sep='\n'.

演示:

>>> 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']
Run Code Online (Sandbox Code Playgroud)