[英]Python: Removing values from a dict which are in range() of each other
我试图从字典中删除彼此相差 2 位以内的值,同时保持相似值的最小值。 对于下面的字典,这意味着只删除了 group2 和 group3,留下 group1,因为 54、55 和 56 都在彼此的两位数之内,并且因为 54 是这三个相似值中最小的,所以它保留在字典。
words = {
"the": 10,
"group1": 54,
"then": 40,
"now": 50,
"group2": 55,
"it": 60,
"group3": 56
}
到 -
words = {
"the": 10,
"group1": 54,
"then": 40,
"now": 50,
"it": 60
}
到目前为止我所拥有的是:
new_dict = {}
words_dup = []
for word, value in words.items():
words_dup.append(value)
for word, value in words.items():
for item in words_dup:
if item-value in range(-2,2):
words_dup.remove(item)
new_dict[word] = value
我的方法很草率,只是从字典中删除随机键值。 有什么更好的方法可以解决这个问题,也许不需要像我上面那样创建新列表和字典。 谢谢你。
也许这更好? 它是 O(n^2),但我怀疑如果没有更复杂的数据结构,你能得到比这更好的结果:
words = {
"the": 10,
"group1": 54,
"then": 40,
"now": 50,
"group2": 55,
"it": 60,
"group3": 56
}
new_dict = {key: val for key, val in words.items()
if all(abs(val - v) > 2 for k, v in words.items() if k != key)}
print(new_dict)
# {'the': 10, 'then': 40, 'now': 50, 'it': 60}
如果需要保持最小元素:
new_dict = {key: val for key, val in words.items()
if all(not 0 < val - v <= 2 for k, v in words.items() if k != key)}
print(new_dict)
# {'the': 10, 'group1': 54, 'then': 40, 'now': 50, 'it': 60}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.