3 回答

TA貢獻1797條經驗 獲得超6個贊
您可以使用all:
>>> from itertools import chain
>>> l = ['A', 'C', 'Z', 'M']
>>> d1 = {'A': 3,'F': 4,'Z': 1}
>>> d2 = {'B': 0,'A': 3,'C': 7}
>>> all( x not in chain(d1,d2) or ((x in d1 and x in d2) and \
d1.get(x) == d2.get(x)) for x in l)
False
>>> l = ['Z']
>>> d1 = {'A': 3,'F': 4,'Z': None}
>>> all( x not in chain(d1,d2) or ((x in d1 and x in d2) and \
d1.get(x) == d2.get(x)) for x in l)
False
all將返回True只有在迭代的所有值都Trueothwerwise它會返回False。

TA貢獻1828條經驗 獲得超13個贊
嘗試這個:
success = True
for x in l:
if not (((x not in d1) and (x not in d2)) or (d1.get(x) == d2.get(x))):
success = False
添加回答
舉報