具有不同长度的列表列表的元素级串联

Element wise concatenation of a list of lists with different lengths

我有一个示例列表,例如:

lol = [[1,2,3,4],[5,6],[7,8,9,0,11],[21]]

预期的组合列表是:

cl = [1,5,7,21,2,6,8,3,9,4,0,11]

有没有一种优雅的方式最好不用嵌套的 for 循环来做到这一点?

您可以使用 itertools.zip_longest:

from itertools import zip_longest

lol = [[1, 2, 3, 4], [5, 6], [7, 8, 9, 0, 11], [21]]

out = [i for v in zip_longest(*lol) for i in v if not i is None]
print(out)

打印:

[1, 5, 7, 21, 2, 6, 8, 3, 9, 4, 0, 11]

itertools 是你的朋友。使用 zip_longest 压缩忽略不同长度,将其链接以展平压缩列表,然后仅过滤 Nones。

lol = [[1,2,3,4],[5,6],[7,8,9,0,11],[21]]
print([x for x in itertools.chain.from_iterable(itertools.zip_longest(*lol)) if x is not None])

如果有帮助,zip_longest 的生成器版本可用作 more_itertools.interleave_longest

from more_itertools import interleave_longest, take

lol = [[1, 2, 3, 4], [5, 6], [7, 8, 9, 0, 11], [21]]
gen_from_lol = interleave_longest(*lol)

print(next(gen_from_lol), next(gen_from_lol))
print(take(6, gen_from_lol))
print(next(gen_from_lol))
print(next(gen_from_lol), next(gen_from_lol))

输出

1 5
[7, 21, 2, 6, 8, 3]
9
4 0

注意interleave_longest(*iterables)chain.from_iterable(zip_longest(*iterables))基本相同