简体   繁体   English

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

[英]How to print nested lists using nested loops?

Hi i have a simplified example of my problem. 嗨,我有我的问题的简化示例。

i would like to get an output of 我想得到一个输出

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

I have tried different variations but can figure out the logic. 我尝试了不同的变体,但可以弄清楚逻辑。 My code is below. 我的代码如下。 Thanks for your help in advance. 感谢您的帮助。 I am trying to do it without using numpy or panda. 我正在尝试不使用numpy或panda。 I am using python3.4 我正在使用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)

Note that you are trying to print the contents of two lists. 请注意,您正在尝试打印两个列表的内容。 This is a linear operation in time. 这是时间上的线性运算。 Two loops just won't cut it - that's quadratic in time complexity. 两个循环不会消除它-时间复杂度是二次方。 Furthermore, your second solution doesn't flatten y . 此外,第二个解决方案不会使y变平。


Define a helper function using yield and yield from . 使用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

If you want a list instead, just call foo with a list wrapper around it: 如果您想要一个列表,只需调用foo及其周围的list包装即可:

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

Note that yield from becomes available to use from python3.3 onwards. 请注意, yield from从python3.3起可以使用。

just zip the lists and flatten twice applying itertools.chain 只需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))))

now result yields: 现在result产量:

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

which you can print with: 您可以使用以下命令进行打印:

print(*result,sep="\n")
numlet = [c for n, l in zip(num,let) for c in [n] + l]
for c in numlet:
    print(c)

Flatten the list let using pydash . 拼合名单let使用pydash pydash is a utility library. pydash是一个实用程序库。

Print each element from the concatenated list ( num + pydash.flatten(let) ) 打印串联列表中的每个元素( 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
>>> 

this solution assumes that "num" and "let" have the same number of elements 此解决方案假定“ 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])

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

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