簡體   English   中英

列表列表中的元組列表

[英]list of tuples from list of lists Python

輸入:列表[[1, 2, 3], [5, 6]]東西。

必需輸出 :元組[(1), (1, 2), (1, 2, 3), (5), (5, 6)]

我可以想象如何解決這個問題,但我想Python有一些方便的內置函數

AFAIK沒有內置函數,但通過列表理解很容易實現這個結果:

[tuple(seq[:i]) for seq in list_of_lists for i in range(1,len(seq)+1)]

如果您確實想要每個子列表的所有組合,可以使用itertools來幫助:

from itertools import chain, combinations

lst = [[1, 2, 3], [4, 5]]

def powerset(seq, empty=True):
    for i in range(0 if empty else 1, len(seq)+1):
        for comb in combinations(seq, i):
            yield comb

out = list(chain.from_iterable(powerset(l, False) for l in lst))

這給出了:

out == [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3),   
        (4,), (5,), (4, 5)]

您可以修改此選項以僅過濾與每個子列表的開頭匹配的元組,但如果這就是您想要的Bakuriu的解決方案更有效。

暫無
暫無

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

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