[英]Generate all combinations from multiple lists in python
我有一個數據集,其中包含多個列表,每個列表具有不同數量的元素。 例如。
list1 = ['a','b','c']
list2 = ['d','e']
list3 = ['f','g','h','i']
我想從這些列表中生成所有可能的唯一組合,條件如下:
我該怎么做呢?
我認為這會做到(其中很多步驟可以組合,但保留它們以顯示步驟)
創建一個包含所有項目的新列表
list4 = list1 + list2 + list3
還有另一個列表來遍歷它們以找到所有 5 種組合(您沒有指定訂單或更換,因此請在此處閱讀並根據需要進行更改)
list5 = list(itertools.combinations(list4, 5))
然后從每個列表中刪除沒有元素的項目。
[i for i in list5 if any(j in list1 for j in i) and any(j in list2 for j in i) and any(j in list3 for j in i)]
所以在一行中它可能是:
[i for i in itertools.combinations(list1 + list2 + list3, 5) if any(j in list1 for j in i) and any(j in list2 for j in i) and any(j in list3 for j in i)]
from itertools import product
Suit = [u"\u2666", u"\u2665", u"\u2663", u"\u2660"]
Card = ['A','K','Q','J','10','9','8','7','6','5','4','3','2']
FullDeck = list(product(Card, Suit))
for i in FullDeck:
print(i)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.