我有一本 python 字典
slot_a = 'a'
slot_b = 'b'
# dict which lists all possible conditions
con_dict = {"branch_1": slot_a == 'a' and slot_b == 'b',
"branch_2": slot_a == 'a' and slot_b == 'c'}
現在我想回傳第一個真實條件的密鑰。在這種情況下,它是branch_1.
我的解決方案是:
# Pick only the condition which is set to True
true_branch = [k for k, v in con_dict.items() if v == True]
true_branch
>>> branch_1
由于分支的數量可能很長,我想知道是否有更優雅的方法來獲得相同的結果?!也許if / elif / else然后回傳鍵?甚至是完全不同的東西?最后我需要的是真實條件的名稱。因此,甚至可能不需要使用 dict 。
只求靈感!
uj5u.com熱心網友回復:
您可以嘗試使用迭代器。一旦獲得第一個匹配項,它將立即停止,而無需遍歷整個“物件”。
ks, vs = zip(*con_dict.items()) # decoupling the list of pairs
i = 0
vs = iter(vs) # terms are all booleans
while not next(vs):
i = 1
del vs # "free" the iterator
print(ks[i])
或者
true_branch = next((k for k, condition in con_dict.items() if condition), None)
print(true_branch)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/475784.html
