简体   繁体   English

打印嵌套列表,python

[英]Print nested list, python

I have a nested list like this:我有一个这样的嵌套列表:

nestedList = [[1,2,3],[4,5,6]]

I want to use a for-loop and print the two lists like this:我想使用 for 循环并像这样打印两个列表:

1   4
2   5
3   6

Any suggestions?有什么建议?

Use *nestedList to unpack argument lists values and then zip to iterate over them:使用*nestedList解压缩参数列表值,然后zip以遍历它们:

nestedList = [[1,2,3],[4,5,6]]

for a in zip(*nestedList):
    print(a)

Output:输出:

(1, 4)
(2, 5)
(3, 6)

You can use zip() in for loop and output should be like this :您可以在 for 循环中使用 zip() 并且输出应该是这样的:

(1,4)
(2,5)
(3,6)

or using simple code like this :或使用这样的简单代码:

nestedList = [[1,2,3],[4,5,6]]

l1 = nestedList[0]
l2 = nestedList[1]

for i in range(3):
    print(l1[i],' ',l2[i])

output should be like this :输出应该是这样的:

1   4
2   5
3   6

You can simply use nested for loops to print as expected:您可以简单地使用嵌套的 for 循环按预期打印:

nestedlist = [[1,2,3],[4,5,6]]
for i in range(len(nestedlist)-1):
    for j in range(len(nestedlist[i])):
        print(nl[i][j]," ",nl[i+1][j])

Output:输出:

1   4
2   5
3   6

Use a simple for loop and " ".join() mapping each int in the nested list to a str with map().使用简单的 for 循环和 " ".join() 将嵌套列表中的每个 int 映射到带有 map() 的 str。

Example:例子:

>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> for xs in ys:
...     print(" ".join(map(str, xs)))
... 
1 2 3
4 5 6
7 8 9 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM