无序且允许重复的可散列数据结构 [英] Hashable data structure with no order and allowed duplicates
问题描述
我有元组/列表列表(-1, 0, 1)(-1, 1, 0)(-1, 2, -1)(-1, -1, 2)(0, 1, -1)
I have list of tuples/lists (-1, 0, 1) (-1, 1, 0) (-1, 2, -1) (-1, -1, 2) (0, 1, -1)
我需要它们:(-1, 1, 0)(-1, 2, -1)
I need them to be : (-1, 1, 0) (-1, 2, -1)
我希望 (-1, 0, 1) 和 (-1, 1, 0) 映射到同一事物.我想到了类似 set 的东西,但这会删除元组中可能存在的任何重复项.
I want (-1, 0, 1) and (-1, 1, 0) map to the same thing. I thought of something like set but that would remove any duplicates I might have in the tuple.
在生成新元组时说 (-1,-1,2) 我想执行像
While generating a new tuple say (-1,-1,2) I want to perform a check like
if (-1,-1,2) in seen:
pass
else:
insert(seen, (-1,-1,2))
为此,我需要数据结构对于 O(1) 查找是可散列的.任何想法如何在 Python 中实现它?
for this I need the data structure to be hashable for O(1) lookup. Any ideas how I would implement this in Python?
推荐答案
您可以使用 set
来避免添加映射到同一事物的元素.
You can use set
to avoid adding elements that map to the same thing.
l = [(-1, 0, 1), (-1, 1, 0), (-1, 2, -1), (-1, -1, 2), (0, 1, -1)]
new_l = []
for i in l:
if set(i) not in [set(j) for j in new_l]:
new_l += [i]
print new_l
返回[(-1, 0, 1), (-1, 2, -1)]
编辑
这错误地将一些元组标记为重复.这应该有效:
This incorrectly flags some tuples as duplicates. This should work :
l = [(-1, 0, 1), (-1, 1, 0), (-1, 2, -1), (-1, -1, 2), (0, 1, -1)]
new_l = list(set([tuple(sorted(i)) for i in l]))
print new_l
这篇关于无序且允许重复的可散列数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!