我有下面的字典,我尝试使用下面的代码删除重复的字典。
vertex = {1: (4.0,7.0), 2: (1.0,4.0), 3: (5.0,8.0), 4: (5.0,6.0), 5: (3.0,8.0), 6: (4.0,7.0), 7: (1.0,4.0), 8: (5.0,8.0), 9: (4.0,2.0), 10: (4.0,8.0), 11: (4.0,7.0), 12: (4.0,2.0), 13: (4.0,8.0), 14: (1.0,4.0), 15: (5.0,8.0), 16: (4.0,4.0), 17: (4.0,2.0), 18: (4.0,8.0), 19: (2.0,2.0), 20: (5.0,5.0), 21: (4.0,7.0), 22: (4.0,2.0), 23: (4.0,8.0), 24: (5.0,6.0), 25: (3.0,8.0)}
result = {}
for key,value in vertex.items():
if value not in result.values():
result[key] = value
print result重复的值仍在添加到结果中。
[] (4.0,7.0) - initial result and value to be checked if its already in result
[(4.0,7.0)] (1.0,4.0)
[(4.0,7.0), (1.0,4.0)] (5.0,8.0)
[(4.0,7.0), (1.0,4.0), (5.0,8.0)] (5.0,6.0)
[(4.0,7.0), (1.0,4.0), (5.0,8.0), (5.0,6.0)] (3.0,8.0)
[(4.0,7.0), (1.0,4.0), (5.0,8.0), (5.0,6.0), (3.0,8.0)] (4.0,7.0) - here (4.0,7.0) is being checked and its getting added though it is already there in it as shown in next step.
[(4.0,7.0), (1.0,4.0), (5.0,8.0), (5.0,6.0), (3.0,8.0), (4.0,7.0)] (1.0,4.0)有没有人能告诉我到底哪里出了问题?我无法弄清楚这一点!谢谢。
发布于 2017-09-28 13:56:39
由于您正在处理唯一的元组,因此set()在这种情况下可以执行得更好。试试这个:
vertex_set = set()
results = {}
for key, value in vertex.items():
if not value in vertex_set:
result[key] = value
vertex_set.add(value)有关集合的更多信息,请参阅https://docs.python.org/2/library/sets.html
https://stackoverflow.com/questions/46456787
复制相似问题