Python 3.x 在Python3中交错多个可变长度列表
这个答案是: 这段代码完全符合我的项目要求,但在python3中不起作用 我使用以下方法解决了这些错误:Python 3.x 在Python3中交错多个可变长度列表,python-3.x,Python 3.x,这个答案是: 这段代码完全符合我的项目要求,但在python3中不起作用 我使用以下方法解决了这些错误: func = lambda *x: x modules = [y for x in map(func,l1,l2,l3) for y in x] 但它现在无法处理可变长度的列表,现在一旦用尽最短的列表就会停止。看起来您需要itertools.zip\u longest from itertools import zip_longest l1=[1,2,3] l2=[10,20,30] l3
func = lambda *x: x
modules = [y for x in map(func,l1,l2,l3) for y in x]
但它现在无法处理可变长度的列表,现在一旦用尽最短的列表就会停止。看起来您需要
itertools.zip\u longest
from itertools import zip_longest
l1=[1,2,3]
l2=[10,20,30]
l3=[101,102,103,104]
print([y for x in zip_longest(l1,l2,l3, fillvalue=None) for y in x if y is not None])
输出:
[1, 10, 101, 2, 20, 102, 3, 30, 103, 104]
看起来您需要
itertools.zip\u
from itertools import zip_longest
l1=[1,2,3]
l2=[10,20,30]
l3=[101,102,103,104]
print([y for x in zip_longest(l1,l2,l3, fillvalue=None) for y in x if y is not None])
输出:
[1, 10, 101, 2, 20, 102, 3, 30, 103, 104]
如果它们是列表,您也可以在所有列表中填充None
:
longest_len = max(len(l1), len(l2), len(l3))
zipped_lists = zip(
l1+[None]*(longest_len-len(l1)),
l2+[None]*(longest_len-len(l2)),
l3+[None]*(longest_len-len(l3)))
modules = [y for x in zipped_lists for y in x if y is not None]
如果它们是列表,您也可以在所有列表中填充None
:
longest_len = max(len(l1), len(l2), len(l3))
zipped_lists = zip(
l1+[None]*(longest_len-len(l1)),
l2+[None]*(longest_len-len(l2)),
l3+[None]*(longest_len-len(l3)))
modules = [y for x in zipped_lists for y in x if y is not None]
您是否考虑过zip(l1、l2、l3)
?整个问题列出了多个其他答案。你试过其中任何一种吗?@Mehdi的可能副本我相信当最短的列表出现时,zip也会停止exhausted@JohnZwinck我相信这是这个问题的一个超集,因为我需要处理可变长度列表。你考虑过zip(l1,l2,l3)
?整个问题列出了多个其他答案。你试过其中任何一种吗?@Mehdi的可能副本我相信当最短的列表出现时,zip也会停止exhausted@JohnZwinck我相信这是这个问题的超集,因为我需要处理可变长度的列表