[英]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.