Python:for循环内部print()

时间:2013-12-25 16:07:58

标签: python list python-3.x printing

我对Python(3.3.2)有疑问。

我有一个清单:

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

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

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

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

我知道我可以这样做:

for list in L:
    print(list)

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

4 个答案:

答案 0 :(得分:18)

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

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

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

演示:

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

如果 要使用循环,请在列表解析中执行此操作:

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

这将在'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']

答案 1 :(得分:3)

这有效:

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

答案 2 :(得分:2)

为我工作:

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

这个也有效:

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

这个也是:

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

答案 3 :(得分:1)

如果有人在dict打印中寻求帮助,那么你去吧:

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


print ('\n'.join(' : '.join(b for b in a) for a in dictionary.items()))
相关问题