我正在尋找一個函式found_in_color_dict(),它告訴我是否可以在color_dict. 該函式分別回傳 True 或 False。
color_dict = {"a":"blue", "b":"green", "c":"yellow", "d":"red", "e":"black", "f":"white"}
checkpoints_1 = {"a":"blue"}
checkpoints_2 = {"a":"green"}
checkpoints_3 = {"a":"blue", "d":"red"}
checkpoints_4 = {"a":"blue", "d":"red", "f":"white"}
checkpoints_5 = {"a":"blue", "d":"red", "f":"purple"}
根據示例,我希望得到以下結果:
found_in_color_dict(checkpoints_1)
>>> True
found_in_color_dict(checkpoints_2)
>>> False
found_in_color_dict(checkpoints_3)
>>> True
found_in_color_dict(checkpoints_4)
>>> True
found_in_color_dict(checkpoints_5)
>>> False
我只能想出復雜的方法來解決這個問題。但我想可能有一個簡單的方法來解決它,對吧?
uj5u.com熱心網友回復:
您可以使用set.issubset:
注意:dict.itemview作為一個集合
def found_in_color_dict(checkpoint):
return checkpoint.items() <= color_dict.items()
>>> found_in_color_dict(checkpoints_1)
True
>>> found_in_color_dict(checkpoints_2)
False
>>> found_in_color_dict(checkpoints_3)
True
>>> found_in_color_dict(checkpoints_4)
True
>>> found_in_color_dict(checkpoints_5)
False
uj5u.com熱心網友回復:
你可以all()這樣使用:
color_dict = {"a":"blue", "b":"green", "c":"yellow", "d":"red", "e":"black", "f":"white"}
def found_in_color_dict(d):
global color_dict
return all(i in color_dict.items() for i in d.items())
測驗代碼:
checkpoints_1 = {"a":"blue"}
checkpoints_2 = {"a":"green"}
checkpoints_3 = {"a":"blue", "d":"red"}
checkpoints_4 = {"a":"blue", "d":"red", "f":"white"}
checkpoints_5 = {"a":"blue", "d":"red", "f":"purple"}
print(found_in_color_dict(checkpoints_1),
found_in_color_dict(checkpoints_2),
found_in_color_dict(checkpoints_3),
found_in_color_dict(checkpoints_4),
found_in_color_dict(checkpoints_5))
輸出:
True False True True False
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436884.html
上一篇:平均字典串列的值
