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

2024-04-20 14:38:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三个元素的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中如何做到这一点?你知道吗


Tags: 项目元素示例列表list2list1l12l11
1条回答
网友
1楼 · 发布于 2024-04-20 14:38:01

由于您最多只需要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)])

相关问题 更多 >