Python从不同长度的多个列表中获取唯一对

2024-10-01 13:41:04 发布

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

假设在Python中我有3个可变长度的列表:a, b, c。例如:

a=[1,2,3]
b=[4,5,6]
c=[7,8]

我想得到以上3个列表中两个元素的每一个独特的组合,即

[1,4],[1,5],[1,6],[1,7],[1,8],[2,4],[2,5]...和3个列表的非唯一组合(例如[1,4,7],[1,4,8],...)。在

我已经研究过使用itertoolssolution here,这对于两个列表来说是非常好的;但是,当包含第n个列表时,这个解决方案不再有效,因为唯一组合的长度是n。在

以下是我尝试过的:

^{pr2}$

注意:以上只是一个例子,解决方案应该适用于长度可变的n列表,并且可能在不同的列表中有相同的值。。。如果你知道我能做什么,我将不胜感激!:)


编辑:正如@SirParselot所要求的,元素必须来自不同的列表


Tags: 元素编辑列表here解决方案例子itertoolssolution
2条回答

我想您应该做的是使用两个列表的工作解决方案来处理n列表。基本上,您可以将输入转换为列表列表,然后执行以下操作:

for index, left_list in enumerate(list_of_lists):
        other_lists = (list_of_lists[0:index] + list_of_lists[index+1:])
        right_list = [i for sublist in other_lists for i in sublist]
        print(list(itertools.product(left_list, right_list)))

您需要(a, b, c)中每对列表的Cartesian product,因此首先需要{a2}来生成列表对,然后{a3}来创建所需的输出元组。在

from itertools import combinations, product

def pairs(*lists):
    for t in combinations(lists, 2):
        for pair in product(*t):
            yield pair

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8]

for pair in pairs(a, b, c):
    print(pair)

输出

^{pr2}$

这是一个处理重复元素的新版本。如果元组中的两个项相等,则不返回元组,并且还通过将pairs中的输出输入到一个集合中来消除输出中重复的元组。这是相当有效的,因为pairs是一个生成器,所以当发现重复项时,就会消除它们。在

from itertools import combinations, product

def pairs(*lists):
    for t in combinations(lists, 2):
        for pair in product(*t):
            #Don't output pairs containing duplicated elements 
            if pair[0] != pair[1]:
                yield pair

a = [1, 2, 3]
b = [3, 4, 5]
c = [5, 6]

#Feed the output of `pairs` into a set to eliminate duplicate tuples
output = set(pairs(a, b, c))
for pair in sorted(output):
    print(pair)

输出

(1, 3)
(1, 4)
(1, 5)
(1, 6)
(2, 3)
(2, 4)
(2, 5)
(2, 6)
(3, 4)
(3, 5)
(3, 6)
(4, 5)
(4, 6)
(5, 6)

相关问题 更多 >