[英]Get combination of sublists with length n
假設我有一個列表lst = [[[24, 25], [25, 26], [25, 35]], [[24, 25, 26], [26, 36, 46]]]
。 我想計算來自其他子列表的所有元素的所有組合,但不是同一個子列表。 在這個例子中它將是:
[[24, 25], [24, 25, 26]],
[[25, 26], [24, 25, 26]],
[[25, 35], [24, 25, 26]],
[[24, 25], [26, 36, 46]],
[[25, 26], [26, 36, 46]],
[[25, 35], [26, 36, 46]]
然而,這也應該能夠產生超過 2 個元素的組合,即lst = [[[1]], [[2], [3]], [[4], [5]]]; (length=len(lst) -> 3)
lst = [[[1]], [[2], [3]], [[4], [5]]]; (length=len(lst) -> 3)
:
[[1], [2], [4]],
[[1], [2], [5]],
[[1], [3], [4]],
[[1], [3], [5]]
我嘗試使用itertools.combinations(*lst)
但只有長度為 2 的.netted 元組。如何實現長度n與上述限制的組合?
使用itertools.product
生成兩個或多個可迭代對象的笛卡爾積:
from itertools import product
top = [[[24, 25], [25, 26], [25, 35]], [[24, 25, 26], [26, 36, 46]]]
for combo in product(*top):
print(combo)
輸出:
([24, 25], [24, 25, 26])
([24, 25], [26, 36, 46])
([25, 26], [24, 25, 26])
([25, 26], [26, 36, 46])
([25, 35], [24, 25, 26])
([25, 35], [26, 36, 46])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.