首页 > 解决方案 > 如何获得所有可能的解决方案以从列表中删除重复项(python)

问题描述

如果我有这样的列表 [C, B, A, B] 并且我想获得所有可能的解决方案来删除重复项:[C, B, A], [C, A, B] 我怎样才能得到这个结果纯蟒蛇?

标签: pythonlist

解决方案


Here, I believe, is an approach that works. First, create a mapping from all the items in the list to their indices:

>>> from collections import defaultdict
>>> data = ['C', 'B', 'D', 'A', 'B', 'E', 'D', 'G','H','D', 'J']
>>> grouped = defaultdict(list)
>>> for i, e in enumerate(data):
...     grouped[e].append(i)
...
>>> grouped
defaultdict(<class 'list'>, {'C': [0], 'B': [1, 4], 'D': [2, 6, 9], 'A': [3], 'E': [5], 'G': [7], 'H': [8], 'J': [10]})

Then, you can simply find the product of all these indices, and reconstitute a list:

>>> import itertools
>>> for idx in itertools.product(*grouped.values()):
...     idx = sorted(idx)
...     print([data[i] for i in idx])
...
['C', 'B', 'D', 'A', 'E', 'G', 'H', 'J']
['C', 'B', 'A', 'E', 'D', 'G', 'H', 'J']
['C', 'B', 'A', 'E', 'G', 'H', 'D', 'J']
['C', 'D', 'A', 'B', 'E', 'G', 'H', 'J']
['C', 'A', 'B', 'E', 'D', 'G', 'H', 'J']
['C', 'A', 'B', 'E', 'G', 'H', 'D', 'J']

Not sure if it is the most elegant. And think there is an edge-case where you will end up with the same result multiple times, e.g. ['C', 'A','A','B'] would give ['C','A','B'], ['C','A','B'], but it isn't clear if that is undesirable, if it is, you could just filter out those duplicates, maybe using a set. But I'll leave that as an exercise for the reader :)


推荐阅读