python - 返回两个字典的差异并减去它的值
问题描述
以下是我的代码。我有一个列表 [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
解决方案
创建一个计数器并将其从平衡的内容中减去:
ctr = Counter(list_elem)
bal = Counter(dict.fromkeys(ctr, max(ctr.values())))
o = dict(bal - ctr)
推荐阅读
- terraform - Cannot taint null_resource
- javascript - 在表单中单击下一步时如何添加幻灯片效果?
- arrays - Scala function that accepts array argument and returns a mutated array
- python - 数据框中的 Python Spark 子字符串
- cumulocity - How to connect to Cumulocity services in order to add multiple devices data
- sql - Oracle Regexp_Substr 或 Regexp_Replace 查询,不满足所有情况
- hugo - How to create a custom list page with only draft posts in Hugo?
- javascript - some() function is not working with && operator
- jquery - bootstrap 4 custom fade in effect
- laravel - Laravel VUE JS 动态下拉菜单