从列表中删除列表的重复元组

时间:2018-05-07 15:10:57

标签: python python-3.x list tuples unique

我想编写一个脚本来获取类别列表,并返回将类别拆分为2组的独特方法。现在我以元组形式(list_a,list_b)使用它,其中list_a和list_b的并集代表完整的类别列表。

下面我展示了一个类别['A','B','C','D']的示例,我可以获得所有组。然而,有些是重复的(['A'],['B','C','D'])代表与(['B','C','D'],['A'相同的分裂])。我如何只保留唯一的分裂?还有什么是这篇文章更好的标题?

import itertools
def getCompliment(smallList, fullList):
    compliment = list()
    for item in fullList:
        if item not in smallList:
            compliment.append(item)
    return compliment

optionList = ['A','B','C','D']
combos = list()
for r in range(1,len(optionList)):
    tuples = list(itertools.combinations(optionList, r))
    for t in tuples:
        combos.append((list(t),getCompliment(list(t), optionList)))

print(combos)

[(['A'], ['B', 'C', 'D']),
 (['B'], ['A', 'C', 'D']), 
 (['C'], ['A', 'B', 'D']),
 (['D'], ['A', 'B', 'C']),
 (['A', 'B'], ['C', 'D']),
 (['A', 'C'], ['B', 'D']),
 (['A', 'D'], ['B', 'C']),
 (['B', 'C'], ['A', 'D']),
 (['B', 'D'], ['A', 'C']),
 (['C', 'D'], ['A', 'B']),
 (['A', 'B', 'C'], ['D']),
 (['A', 'B', 'D'], ['C']),
 (['A', 'C', 'D'], ['B']),
 (['B', 'C', 'D'], ['A'])]

我需要以下内容:

[(['A'], ['B', 'C', 'D']),
 (['B'], ['A', 'C', 'D']), 
 (['C'], ['A', 'B', 'D']),
 (['D'], ['A', 'B', 'C']),
 (['A', 'B'], ['C', 'D']),
 (['A', 'C'], ['B', 'D']),
 (['A', 'D'], ['B', 'C'])]

1 个答案:

答案 0 :(得分:3)

你非常接近。您需要的是set个结果。

由于set元素必须是可清除的,并且list个对象不可清除,因此您可以使用tuple。这可以通过对代码进行一些微不足道的更改来实现。

import itertools

def getCompliment(smallList, fullList):
    compliment = list()
    for item in fullList:
        if item not in smallList:
            compliment.append(item)
    return tuple(compliment)

optionList = ('A','B','C','D')
combos = set()
for r in range(1,len(optionList)):
    tuples = list(itertools.combinations(optionList, r))
    for t in tuples:
        combos.add(frozenset((tuple(t), getCompliment(tuple(t), optionList))))

print(combos)

{frozenset({('A',), ('B', 'C', 'D')}),
 frozenset({('A', 'C', 'D'), ('B',)}),
 frozenset({('A', 'B', 'D'), ('C',)}),
 frozenset({('A', 'B'), ('C', 'D')}),
 frozenset({('A', 'C'), ('B', 'D')}),
 frozenset({('A', 'D'), ('B', 'C')}),
 frozenset({('A', 'B', 'C'), ('D',)})}

如果您需要将结果转换回列表列表,可以通过列表理解来实现:

res = [list(map(list, i)) for i in combos]

[[['A'], ['B', 'C', 'D']],
 [['B'], ['A', 'C', 'D']],
 [['A', 'B', 'D'], ['C']],
 [['A', 'B'], ['C', 'D']],
 [['B', 'D'], ['A', 'C']],
 [['B', 'C'], ['A', 'D']],
 [['A', 'B', 'C'], ['D']]]