我有一个列表:l = [1, (2, 3), (4, 5), 6]
我想从此列表中选择3个项目,但每个子列表只能选择一个项目。
使用combinations
我可以实现:
Result = [[1, (2, 3), (4, 5)], [1, (2, 3), 6], [1, (4, 5), 6]]
然而,元组没有扩展。产生该列表中所有项目组合列表的最Pythonic方法是什么?
示例输出:
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]]
答案 0 :(得分:3)
您可以将combinations
与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)]
我首先将seq
转换为元组列表(即使元组只有一个元素),因为这会使以后的操作更加自然。