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

在Python中使用唯一索引的所有列表组合,python,list,find,Python,List,Find,我有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,

我有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置换。例如,
排列(列表,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)])

澄清一下:最后一个数字在组合中总是唯一的。那么
combinasion2
呢?您已经使用了两次相同的元素
l11、l23、l31
使用了两次相同的索引。对我来说,它不是相同的索引。l11使用列表中的索引0 l23使用列表中的索引1 l31使用列表中的索引2感谢Jason,但例如,使用4个列表。。。您的代码无效。@Matt在您的问题中,您从未使用过3以外的数字。为什么我们会期望4个?我说过,“我有n个列表”,列表的数量并不总是3个。我可以有3,4,5,6个列表。更新为不同的N。完美!非常感谢杰森!你的解决方案很好。