python - 如何获得所有可能的解决方案以从列表中删除重复项(python)
问题描述
如果我有这样的列表 [C, B, A, B] 并且我想获得所有可能的解决方案来删除重复项:[C, B, A], [C, A, B] 我怎样才能得到这个结果纯蟒蛇?
解决方案
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 :)
推荐阅读
- spring-boot - 使用 spring-boot 启动 apache tomcat 时出现以下错误
- python - CSPRNG Python 2.7 实现
- python-3.x - 优先队列比较和更新
- wpf - 如何绑定 wpf 用户控件?
- c# - API 返回的部分 JSON 由 JSON.NET 序列化,但不是全部
- c# - WPF DataGrid的列索引
- document - MongoEngine:从嵌入文档中获取父文档
- php - Gravityforms not found 消息 - WP 插件挂钩
- entity-framework - 是否可以改善 EF6 预热时间?
- c - c语言问一个三角形公式