如何检查字典中的值是否都具有相同的值X? [英] How do I check if values in a dictionary all have the same value X?
本文介绍了如何检查字典中的值是否都具有相同的值X?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字典,我正在尝试检查所有具有相同数值(例如1)的值是否罕见.
I have a dictionary, and I'm trying to check for the rare occurrence of all values having the same numerical value, say 1. How would I go about doing this in an efficient manner?
推荐答案
我假设您的意思是相同的值:
I will assume you meant the same value:
d = {'a':1, 'b':1, 'c':1}
len(set(d.values()))==1 # -> True
如果要检查特定值,怎么办
If you want to check for a specific value, how about
testval = 1
all(val==testval for val in d.values()) # -> True
此代码通常会在早期(快速)失败
this code will most often fail early (quickly)
这篇关于如何检查字典中的值是否都具有相同的值X?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文