繁体   English   中英

从python中的列表列表创建列表的所有组合

[英]Create all combinations of lists from a list of lists in python

我有一个列表: 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]]

您可以将combinationsproduct combinations

>>> 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转换为元组列表(即使元组仅包含一个元素),因为这样会使以后的操作更加自然。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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