簡體   English   中英

具有不同長度的列表列表的元素明智連接

[英]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到 zip 忽略不同的長度,將其鏈接以展平壓縮列表,然后僅過濾None s。

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))

Output

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM