检查字典的任何值是否与条件匹配 [英] Check if any value of a dictionary matches a condition
本文介绍了检查字典的任何值是否与条件匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
python 程序员如何检查字典的任何值是否与条件匹配(在我的情况下大于 0
).我正在寻找对性能影响最小的最pythonic"方式.
我的字典:
pairs = { 'word1':0, 'word2':0, 'word3':2000, 'word4':64, 'word5':0, 'wordn':8 }
到目前为止,我使用了这 2 个(可怕的?)方法.
1:
options =pairs.values() # 提取值对于我的选项:如果我>0:返回真返回错误
2:
options = sorted(pairs.items(), key=lambda e: e[1], reverse=True) # 从最大到最小排序如果选项[0][1] >0:返回真别的:返回错误
解决方案
您可以使用 any
[文档]:
另见all
[文档]:
由于您使用的是 Python 2.7,.itervalues()
可能比 .values()
好一点,因为它不会创建新列表.
How does a python programmer check if any value of a dictionary matches a condition (is greater than 0
in my case). I'm looking for the most "pythonic" way that has minimal performance-impact.
my dictionary:
pairs = { 'word1':0, 'word2':0, 'word3':2000, 'word4':64, 'word5':0, 'wordn':8 }
I used these 2 (monstrous?) methods so far.
1:
options = pairs.values() # extract values
for i in options:
if i > 0:
return True
return False
2:
options = sorted(pairs.items(), key=lambda e: e[1], reverse=True) # rank from max to min
if options[0][1] > 0:
return True
else:
return False
解决方案
You can use any
[docs]:
>>> pairs = { 'word1':0, 'word2':0, 'word3':2000, 'word4':64, 'word5':0, 'wordn':8 }
>>> any(v > 0 for v in pairs.itervalues())
True
>>> any(v > 3000 for v in pairs.itervalues())
False
See also all
[docs]:
>>> all(v > 0 for v in pairs.itervalues())
False
>>> all(v < 3000 for v in pairs.itervalues())
True
Since you're using Python 2.7, .itervalues()
is probably a little better than .values()
because it doesn't create a new list.
这篇关于检查字典的任何值是否与条件匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文