我有一本看起來像這樣的字典:
word_freq = {
"Hello": 56,
"at": 23,
"test": 43,
"this": 78
}
和值串列 list_values = [val1, val2]
我需要檢查所有values: val1 and val2in 是否list_values作為word_freqdict 中的值存在。
我試圖用is函式解決問題:
def check_value_exist(test_dict, value1, value2):
list_values = [value1, value2]
do_exist = False
for key, value in test_dict.items():
for i in range(len(list_values)):
if value == list_values[i]:
do_exist = True
return do_exist
必須有一種直接的方法來做到這一點,但我還是 python 的新手,無法弄清楚。如果 word_freq 中的展位值無效,則嘗試過。
uj5u.com熱心網友回復:
這應該做你想做的:
def check_value_exist(test_dict, value1, value2):
return all( v in test_dict for v in [value1,value2] )
uj5u.com熱心網友回復:
做values一組,您可以使用set.issubset來驗證所有值都在dict:
def check_value_exist(word_freq, *values):
return set(values).issubset(word_freq)
print(check_value_exists(word_freq, 'at', 'test'))
print(check_value_exists(word_freq, 'at', 'test', 'bar'))
True
False
uj5u.com熱心網友回復:
一種方法:
def check_value_exist(test_dict, value1, value2):
return {value1, value2} <= set(test_dict.values())
print(check_value_exist(word_freq, 23, 56))
print(check_value_exist(word_freq, 23, 42))
輸出
True
False
由于您將值作為引數接收,因此您可以構建一個集合并驗證該集合是否是 dict 值的子集。
如果您正在檢查鍵,而不是值,這應該就足夠了:
def check_value_exist(test_dict, value1, value2):
return {value1, value2} <= test_dict.keys()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350554.html
