我試圖用 2 個物件編碼條件,它們的條件可以交換。看起來像:
# pseudo code
if (obj_a meets condition_a and obj_b meets condition_b) or
(obj_a meets condition_b and obj_b meets condition_a): return True
else: return False
編輯:如果所有條件以任何順序滿足不同的物件,則該函式應回傳 True
但這似乎非常硬編碼,如果我有更多的物件和更多的條件,那將是一堆交換條件的相同行。我如何設法有效地編碼?例如:
# objs are Capitalized, conditions have a trailing tail for easier reading. (pseudo code)
if (A.a_ and B.b_ and C.c_) or
(A.b_ and B.c_ and C.a_) or
(A.c_ and B.a_ and C.b_) or
(A.b_ and B.a_ and C.c_) or
(A.c_ and B.b_ and C.a_) or
(A.a_ and B.c_ and C.b_): return True
else: return False
uj5u.com熱心網友回復:
如果objects是您想要應用條件的物件序列,并且condition是檢查相關條件的某個函式,那么您可以使用內置函式any和itertools.permutations作為
any(condition(perm) for perm in itertools.permutations(objects))
使用問題中的示例,我們可以有
import itertools
def condition(a, b, c) -> bool:
return a.a_ and b.b_ and c.c_
objects = [A, B, C]
if any(condition(*perm) for perm in itertools.permutations(objects)):
# Condition passed for some permutation.
else:
# Condition did not pass for any permutation.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362774.html
下一篇:根據用戶輸入對字典使用for回圈
