简体   繁体   中英

list of tuples from list of lists Python

Input: List of lists [[1, 2, 3], [5, 6]] something like that.

Required Output : list of combinations in tuples [(1), (1, 2), (1, 2, 3), (5), (5, 6)] .

I can imagine how to solve this, but I guess Python has some handy built-in functions for that

AFAIK没有内置函数,但通过列表理解很容易实现这个结果:

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

If you actually want all combinations of each sublist, you can use itertools to help:

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

This gives:

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

You could modify this to filter just the tuples matching the start of each sublist, but if that's all you want Bakuriu's solution is more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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