簡體   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