gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:45:24 24 4
gpt4 key购买 nike

我想编写一个脚本来获取类别列表并返回将类别分为 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'])]

最佳答案

你们很亲近。您需要的是一组 结果。

由于 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']]]

关于python - 从列表中删除重复的列表元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50217367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com