[英]Counting number of keys that have specific values in a range
I have the following problem. 我有以下问题。 I have a dictionary with coordinates as keys and values that lay between 0 and something like 0.0026.
我有一本字典,它的坐标为键,值在0到0.0026之间。 Now I want to count the number of keys that have values between 0.0013 and 0.0026 for example.
现在,我想计算例如值在0.0013到0.0026之间的键的数量。 How can I do that?
我怎样才能做到这一点?
For example: 例如:
dict1 ={(0,1,2):"0.0026",(0,4,2):"0.0011",(0,5,2):"0.0018"}
You could simply use a sum
with a conditional generator expression: 您可以简单地将
sum
与条件生成器表达式一起使用:
>>> sum(1 for val in dict1.values() if 0.0013 < float(val) < 0.0026)
1
If you want to use "normal" for
-loops you could also use: 如果要
for
-loops使用“ normal” for
则还可以使用:
sum_ = 0
for val in dict1.values():
if 0.0013 < float(val) < 0.0026:
sum_ += 1
Depending on your understanding of "between" you need to change the <
to <=
. 根据您对“之间”的理解,需要将
<
更改为<=
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.