我試圖弄清楚如何比較兩個具有不同鍵數的字典。例如,這里有兩個字典:
person = {'name': 'John', 'birthYear': 1995, 'month': 1}
time = {'birthYear': 1995, 'month': 1}
我想撰寫代碼,如果第二個(birthYear)和第三個(month)鍵在時間上與第一個(birthYear)和第二個(month)鍵匹配,程式將列印出這個人的名字(或者比較只是稱其為真的)。有沒有辦法這樣做?我對 Python 很陌生。
uj5u.com熱心網友回復:
嘗試類似:
person = {'name': 'John', 'birthYear': 1995, 'month': 1}
time = {'birthYear': 1995, 'month': 1}
if all(person[key] == time[key] for key in ['birthYear', 'month']):
print(person['name'])
uj5u.com熱心網友回復:
當然有:試試
if person['birthYear'] == time['birthYear'] and person['month'] == time['month']:
print(person['name'])
只需使用 if 陳述句來檢查兩個條件并在它們都通過測驗時列印結果
您還可以像這樣嵌套條件陳述句:
if person['birthYear'] == time['birthYear']: # this must be true
if person['month'] == time['month']: # and this must be true
print(person['name']) # for this to print
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479602.html
上一篇:從資料框到嵌套字典
