python程序員如何檢查字典的任何值是否與條件匹配(在我的情況下大於0
)。我正在尋找對性能影響最小的「pythonic」方式。檢查字典的任何值是否與條件匹配
我的字典裏:
pairs = { 'word1':0, 'word2':0, 'word3':2000, 'word4':64, 'word5':0, 'wordn':8 }
我用這2(可怕的?)方法爲止。
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
您是否正在檢查字典中的一個條目(如您的文本所述)或所有條目(如您的代碼所做的)? – smcg
@smcg:對不起,我的英語。我的意思是所有的條目;] – Firebowl2000