python - 根据可能值列表计算列表中的元素

标签 python list counter

我有一个列表如下:

a = [50, 75, 75, 100, 50, 50, 75, 50, 75]

可能的值为:0,25,50,75 和 100

从那里我想将字典中的值分组为:

result= {'0':0,'25':0,'50':4,'75':4,'100':1}

我尝试过收藏:

import collections
a = [50, 75, 75, 100, 50, 50, 75, 50, 75]
counter=collections.Counter(a)

但是结果:

Counter({50: 4, 75: 4, 100: 1})

不考虑:'0':0,'25':0

如何将选项列表传递给此函数或其他函数?

最佳答案

您可以使用 dict.fromkeys() 创建一个默认值为 0 的空字典,然后将其与 Counter() 合并输出:

from collections import Counter

a = [50, 75, 75, 100, 50, 50, 75, 50, 75]
possible =[0,25,50,75, 100]

{**dict.fromkeys(possible, 0), **Counter(a)}
# {0: 0, 25: 0, 50: 4, 75: 4, 100: 1}

d = dict.fromkeys(possible, 0)
d.update(Counter(a))

关于python - 根据可能值列表计算列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59920790/

相关文章:

python - 如何返回不包括某些列的新数据框?

python - 如何将键值对插入 python 列表?

vhdl - 带 D 触发器的 2 位加 4 位计数器 - VHDL

python - 根据条件设置具有相同编号的计数器或行

python - 将 PIL 黑白图像转换为 Numpy 数组时出错

python - 发布 django 时过滤 csrfmiddlewaretoken

python - 欧拉计划 #35 : nicer way to test if an even integer is 'inside' an integer

python - 根据大数组的第一个元素创建子数组形成大数组

python - 一个 pygame Sprite 列表丢失了它的第一个元素,并获得了最后一个元素的副本

Python:从 txt 文件的目录中计算单词并将单词计数写入单独的 txt 文件