首页 > 解决方案 > 返回两个字典的差异并减去它的值

问题描述

以下是我的代码。我有一个列表 [4,5,11,5,6,11] 中给出的元素列表。我期望的结果输出是数组中的不平衡元素。

from collections import Counter

list_elem = [4,5,11,5,6,11]
dict_elem = dict(Counter(list_elem))
max_val = dict([max(dict_elem.items(), key=lambda x: x[1])])
o={k:v for k,v in dict_elem.items() if k not in max_val or v != max_val[k]}

Expecting o to be {4: 1, 6: 1} not {4: 1, 11: 2, 6: 1}

If the list_elem is [1,5,6,7,1,6,1] then I want the output to be  {5:2,7:2,6:1}
i.e. 3 being the value for the key- 1, and then we need the rest of the values of the keys to have value subtracted from the max, i.e -3

标签: pythondictionary

解决方案


创建一个计数器并将其从平衡的内容中减去:

ctr = Counter(list_elem)
bal = Counter(dict.fromkeys(ctr, max(ctr.values())))
o = dict(bal - ctr)

推荐阅读