Python 2.7计数具有给定值的字典项的数量 [英] Python 2.7 Counting number of dictionary items with given value
问题描述
第一个问题在这里,所以我会得到它:
使用python 2.7
我有一个项目的字典,键是一个表示为元组的x,y坐标:(x,y),所有值都是布尔值。
我正在尝试找出一个快速干净的方法来获得有多少项目具有给定值的计数。我不需要知道哪些键具有给定的值,只有多少。
有一个类似的帖子:
字典中的许多项目在Python中共享相同的值,但是我不需要一个返回的字典,只是一个整数。
我的第一个想法是迭代项目并测试每个项目,同时保持每个True的计数价值还是什么我只是想知道,因为我仍然是新的python,不知道所有的图书馆,如果有一个更好/更快/更简单的方法来做到这一点。
感谢提前。
这第一部分主要是为了有趣 - 我可能不会在我的代码中使用它。
sum(d.values())
将获得 True的数量。 (当然,您可以通过
len(d) - sum(d.values())$ c $获取
False
值的数量c>)。
稍微更一般地说,你可以做一些类似的事情:
sum(1 for x in d.values()if some_condition(x))
在这种情况下,如果x 如果某个如果some_condition(x)
并且是大多数人将在现实世界的代码中使用)
我已经在这里发现了三个解决方案,上面是最真实的是我应该推荐的一个
最后,我想这可以写得更聪明一些: / p>
sum(x == d.values()中x的selected_value)
/ pre>
这与我的第一个(有趣的)解决方案是一样的,因为它依赖于
True + True == 2
。聪明不总是更好。我想大多数人会认为这个版本比上面的一个更加模糊(因此更糟糕)。first question here, so i will get right to it:
using python 2.7
I have a dictionary of items, the keys are an x,y coordinate represented as a tuple: (x,y) and all the values are Boolean values.
I am trying to figure out a quick and clean method of getting a count of how many items have a given value. I do NOT need to know which keys have the given value, just how many.
there is a similar post here: How many items in a dictionary share the same value in Python, however I do not need a dictionary returned, just an integer.
My first thought is to iterate over the items and test each one while keeping a count of each True value or something. I am just wondering, since I am still new to python and don't know all the libraries, if there is a better/faster/simpler way to do this.
thanks in advance.
解决方案This first part is mostly for fun -- I probably wouldn't use it in my code.
sum(d.values())
will get the number of
True
values. (Of course, you can get the number ofFalse
values bylen(d) - sum(d.values())
).
Slightly more generally, you can do something like:
sum(1 for x in d.values() if some_condition(x))
In this case,
if x
works just fine in place ofif some_condition(x)
and is what most people would use in real-world code)OF THE THREE SOLUTIONS I HAVE POSTED HERE, THE ABOVE IS THE MOST IDIOMATIC AND IS THE ONE I WOULD RECOMMEND
Finally, I suppose this could be written a little more cleverly:
sum( x == chosen_value for x in d.values() )
This is in the same vein as my first (fun) solution as it relies on the fact that
True + True == 2
. Clever isn't always better. I think most people would consider this version to be a little more obscure than the one above (and therefore worse).这篇关于Python 2.7计数具有给定值的字典项的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!