python - 计算列表中整数的最优雅方法

标签 python

我正在寻找最优雅的方式来执行以下操作:

假设我想计算每个整数在列表中出现的次数;我可以这样做:

x = [1,2,3,2,4,1,2,5,7,2]

dicto = {}

for num in x:
    try:
        dicto[num] = dicto[num] + 1
    except KeyError:
        dicto[num] = 1

不过,我觉得

try:
    dicto[num] = dicto[num] + 1
except KeyError:
    dicto[num] = 1

不是最优雅的方式;我想我看到上面的代码被一行替换了。执行此操作最优雅的方法是什么?

我意识到这可能是重复的,但我环顾四周,找不到我要找的东西。

提前致谢。

最佳答案

使用计数器类

>>> from collections import Counter
>>> x = [1,2,3,2,4,1,2,5,7,2]
>>> c = Counter(x)

现在你可以使用 Counter 对象 c 作为字典。

>>> c[1]
2
>>> c[10]
0

(这也适用于不存在的值)

关于python - 计算列表中整数的最优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9754030/

相关文章:

python - 为什么 Scipy 中的 ttest_ind 与 Excel TTest 略有不同?

python - 将城市和温度值获取到变量中以在 reducer 文件中使用

python - 使用 run_in_executor 和 asyncio 时的超时处理

python - 如何显示 PySide/PyQt UI 并自动运行其方法之一?

python - 将本地 infile csv 加载到 mysql 数据库失败

python - 如何将 3d 数组 (nxnxn) 围绕 x、y 和 z 轴旋转 x 度?

python - 在带有 ipywidgets 的 jupyter notebook 上使用 nbconvert 时,输出小部件出现在选项卡小部件之外

python - 将 "NoneType object has no attribute"用于自定义上下文管理器时获取 "with ... as"

python - 反编译 .swf 文件以在 python 中获取图像

python - scrapy中通过回调函数传递元元素