简体   繁体   中英

Create all combinations of lists from a list of lists in python

I have a list: l = [1, (2, 3), (4, 5), 6]

I want to choose 3 items from this list, but only one item can be chosen for each sub list. Using combinations I can achieve:

Result = [[1, (2, 3), (4, 5)], [1, (2, 3), 6], [1, (4, 5), 6]]

However the tuples are not expanded. What is the most Pythonic way to produce a list of all the combinations of items within that list?

Example output:

Result = [[1, 2, 4], [1, 2, 5], [1, 2, 6], [1, 3, 4], [1, 3, 5], [1, 3, 6], [2, 4, 6], [2, 5, 6], [3, 4, 6], [3, 5, 6]]

You could combine combinations with product :

>>> from itertools import combinations, product
>>> seq = [1, (2, 3), (4, 5), 6]
>>> seq = [x if isinstance(x, tuple) else (x,) for x in seq]
>>> [sel for subseq in combinations(seq, 3) for sel in product(*subseq)]
[(1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 2, 6), (1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 4, 6), (2, 5, 6), (3, 4, 6), (3, 5, 6)]

where I've converted seq to be a list of tuples (even if the tuples only have one element) first, because that makes later operations much more natural.

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