首页 > 解决方案 > Python中的嵌套循环

问题描述

我正在学习 Python 循环。在下面的代码中,我无法获得所需的输出。

我想将两个嵌套列表值分成两行代码:

list_of_list = [[1,2,3],[4,5,6]]
    for list1 in list_of_list:
        print (list1)
        for x in list1:
            print (x)

期望的输出:

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

我当前的输出:

1
2
3
4
5
6

请就如何达到预期结果提出建议。

标签: pythonpython-3.xfor-loopnestednested-loops

解决方案


几种方式:

1.join

做:

print('\n'.join([str(i) for i in list_of_list]))

2.list comprehension

做:

[print(i) for i in list_of_list]

3.for-loop

做:

for i in list_of_list:
    print(i)

所有输出:

这个:

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

如预期的

解释为什么你的不起作用:

  • 因为循环太多,只需要一个循环

  • 外循环足以满足需要,您有嵌套循环,所以第一个循环(我的意思是外循环)


推荐阅读