如何使用嵌套循环打印嵌套列表?

时间:2017-09-22 13:36:19

标签: python list for-loop nested-loops nested-lists

您好我的问题的简化示例。

我想获得

的输出
1
a
b
2
c
3
d
e
f
4
g
5
h

我尝试了不同的变化,但可以找出逻辑。我的代码如下。感谢您的帮助。我试图不使用numpy或熊猫。我正在使用python3.4

num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]


for x in num :
    print(x)
    for y in let :
        print(y)

zipBoth = zip(num,let)


for x,y in zipBoth :
    print(x)
    print(y)

5 个答案:

答案 0 :(得分:2)

请注意,您正在尝试打印两个列表的内容。这是一个及时的线性操作。两个循环不会削减它 - 这是时间复杂度的二次方。此外,您的第二个解决方案并未展平y

使用yieldyield from定义辅助函数。

def foo(l1, l2):
    for x, y in zip(l1, l2):
        yield x
        yield from y        

for i in foo(num, let):
     print(i)

1
a
b
2
c
3
d
e
f
4
g
5
h

如果您想要一个列表,只需使用foo包装器调用list

print(list(foo(num, let)))
['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']

请注意,yield from可以从python3.3开始使用。

答案 1 :(得分:1)

仅列出zip个列表,并在应用itertools.chain

时展平两次
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]

import itertools

result = list(itertools.chain.from_iterable(itertools.chain.from_iterable(zip(num,let))))

现在result产生:

['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']

你可以打印:

print(*result,sep="\n")

答案 2 :(得分:1)

numlet = [c for n, l in zip(num,let) for c in [n] + l]
for c in numlet:
    print(c)

答案 3 :(得分:0)

使用let展开列表pydashpydash是一个实用程序库。

打印连续列表中的每个元素(num + pydash.flatten(let)

>>> import pydash as pyd
>>> num = ["1" , "2" ,"3" , "4" , "5" ]
>>> let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
>>> for i in [str(j) for j in num + pyd.flatten(let)]:
...     print(i)
1
2
3
4
5
a
b
c
d
e
f
g
h
>>> 

答案 4 :(得分:0)

此解决方案假定“num”和“let”具有相同数量的元素

num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]

for i in range(len(num)):
    print num[i]
    print '\n'.join(let[i])
相关问题