在单独的行中打印列表列表 [英] Print list of lists in separate lines
问题描述
我有一个列表列表:
a = [[1, 3, 4], [2, 5, 7]]
我想要以下格式的输出:
I want the output in the following format:
1 3 4
2 5 7
我已经尝试通过以下方式进行尝试,但是输出的效果不理想:
I have tried it the following way , but the outputs are not in the desired way:
for i in a:
for j in i:
print(j, sep=' ')
输出:
1
3
4
2
5
7
在更改打印调用以改为使用end
时:
While changing the print call to use end
instead:
for i in a:
for j in i:
print(j, end = ' ')
输出:
1 3 4 2 5 7
有什么想法吗?
推荐答案
遍历原始列表中的每个子列表,并使用*
在打印调用中将其解压缩:
Iterate through every sub-list in your original list and unpack it in the print call with *
:
a = [[1, 3, 4], [2, 5, 7]]
for s in a:
print(*s)
默认情况下,分隔设置为' '
,因此无需显式提供分隔.打印:
The separation is by default set to ' '
so there's no need to explicitly provide it. This prints:
1 3 4
2 5 7
在您的方法中,您要对每个子列表中的每个元素进行迭代,并分别进行打印.通过使用print(*s)
您可以解压缩打印调用中的列表,这实际上可以转换为:
In your approach you were iterating for every element in every sub-list and printing that individually. By using print(*s)
you unpack the list inside the print call, this essentially translates to:
print(1, 3, 4) # for s = [1, 2, 3]
print(2, 5, 7) # for s = [2, 5, 7]
这篇关于在单独的行中打印列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!