python - 计算在某个范围内具有特定值的键的数量

标签 python arrays numpy dictionary scipy

我遇到以下问题。我有一本字典,其中坐标作为键,值介于 0 和 0.0026 之间。例如,现在我想计算值在 0.0013 到 0.0026 之间的键的数量。我怎样才能做到这一点?

例如:

dict1 ={(0,1,2):"0.0026",(0,4,2):"0.0011",(0,5,2):"0.0018"}

最佳答案

您可以简单地使用sum使用条件生成器表达式:

>>> sum(1 for val in dict1.values() if 0.0013 < float(val) < 0.0026)
1

如果你想使用“正常”for -你也可以使用循环:

sum_ = 0
for val in dict1.values():
    if 0.0013 < float(val) < 0.0026:
        sum_ += 1

根据您对“之间”的理解,您需要更改 <<= .

关于python - 计算在某个范围内具有特定值的键的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44650974/

相关文章:

python - SQLAlchemy 在 PostgresQL 中创建 View

python - 在保存的图像上裁剪 x 轴标签

C String数组的数组

PHP json_decode 错误 - Mandrill Webhook

Python NumPy : reshape is deprecated

python - Keras 拟合模型 : TypeError: unhashable type: 'numpy.ndarray'

python - 如何从 csv 绘制 Bokeh 多行数据框

python - 找不到满足我自己模块要求的版本

Junit 测试中的 Java ArrayList 填充单个值

python - Python scipy/numpy 中相关性的层次聚类?