簡體   English   中英

如何在Python中實現“if if”?

[英]How could an “also if” be implemented in Python?

我想在概念上實現以下內容:

if condition1:
    action1()
also if condition2:
    action2()
also if condition3:
    action3()
also if condition4:
    action4()
also if condition5:
    action5()
also if condition6:
    action6()
else:
    print("None of the conditions was met.")

實現這樣的邏輯的合理而明確的方法是什么? 怎么可能將else綁定到多個if語句? 我是否會被迫創建一個布爾來跟蹤事物?

我會建議:

if condition1:
    action1()
if condition2:
    action2()
...
if not any(condition1, condition2, ...):
    print(...)

好的,根據澄清,這樣的事情會很好:

class Accumulator(object):
    none = None
    def also(self, condition):
        self.none = not condition and (self.none is None or self.none)
        return condition

acc = Accumulator()
also = acc.also

if also(condition1):
    action1()
if also(condition2):
    action2()
if also(condition3):
    action3()
if also(condition4):
    action4()
if acc.none:
    print "none passed"

您可以擴展它以獲取有關if語句執行的其他信息:

class Accumulator(object):
    all = True
    any = False
    none = None
    total = 0
    passed = 0
    failed = 0

    def also(self, condition):
        self.all = self.all and condition
        self.any = self.any or condition
        self.none = not condition and (self.none is None or self.none)
        self.total += 1
        self.passed += 1 if condition else self.failed += 1 
        return condition
conditionMet = False
if condition1:
    action1()
    conditionMet = True
if condition2:
    action2()
    conditionMet = True
if condition3:
    action3()
    conditionMet = True
if condition4:
    action4()
    conditionMet = True
if condition5:
    action5()
    conditionMet = True
if condition6:
    action6()
    conditionMet = True

if not conditionMet:
    print("None of the conditions was met.")

你可以這樣做:

conditions = [condition1,condition2,condition3,condition4,condition5,condition6]
actions = [action1, action2, action3, action4, action5, action6]

for condition, action in zip(conditions, actions):
    if condition:
        action()

if not any(conditions):
    print("None of the contitions was met")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM