簡體   English   中英

使用Python中唯一索引的列表的所有組合

[英]All combinations of lists using unique indexes in Python

我有3個元素的N個列表。 我想找到它們之間沒有兩次使用相同索引的所有組合。 每個組合必須始終包含3個項目。

例:

list1 = [l11, l12, l13]

list2 = [l21, l22, l23]

list3 = [l31, l32, l33]

所有可能的組合:

combinaison1 = l11, l22, l33

combinaison2 = l11, l23, l32

combinaison3 = l12, l21,l33

combinaison4= l12, l23, l31

combinaison5=l13, l21, l32

combinaison6= l13, l22, l31

但是我不想要:

BADcombinaison = l11,l21,l32

我該如何在python中做到這一點?

由於最多只需要3個或更多列表中的3個項目,因此第一步是用k-3查找列表列表的k個排列。 permutations(lists, 3) 從那里開始,實際上您也不必置換索引,因為您需要唯一的索引。 (注意:這允許可變數量的列表以及可變長度的列表,但是所有輸入和輸出列表的長度均相等)。

從本質上講,而不是嘗試置換索引,索引只是(0,1,2),因為您沒有指定索引重復,並且列表是置換的。

from itertools import permutations

# number of lists may vary (>= length of lists)
list1 = ["l11", "l12", "l13"]
list2 = ["l21", "l22", "l23"]
list3 = ["l31", "l32", "l33"]
list4 = ["l41", "l42", "l43"]
lists = [list1, list2, list3, list4]

# lenths of lists must be the same and will be the size of outputs
size = len(lists[0])
for subset in permutations(lists, size):
    print([sublist[item_i] for item_i, sublist in enumerate(subset)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM