簡體   English   中英

一個條件語句中多個“或”語句的有效方法

[英]Efficient approach for multiple 'or' statements in an conditional statement

剛學習Python才幾個月,所以請多多包涵...

作為Python教程的一部分,創建一個非常簡單的游戲,從本質上講,用戶從一個類跳到另一個類,所有這些都需要用戶輸入並打印出各種語句。

例如,給定以下類別:

class ChipCar(Scene):

    def enter(self):
        print "What's up? Get in the Bran Muffin car!"

        action = raw_input(">  ")

        if action == "shut up chip":
            print "Screw you!"
            print action
            return next_scene('Your_death')
            #return 'Death' 
        elif action == "hi chip":
            print "What's up loser?!?! Let's go to O&A..."
            return next_scene('Chip_in_studio')
        else:
            print "what's wrong with you? Let's go to my mother's house, I think Lamar's there..."
            return 'Chip_mom_house'

假設我希望能夠為第一個if語句檢查多個正確選項,例如,除了"shut up chip"還說"go away dude""screw you""Java sucks" -最好的方法是?

如果所有測試都是相同的,則可以in集合上使用in運算符,它將檢查您要測試的值是否存在。 我建議使用一個set因為它的成員資格測試非常快,但是您可以使用listtuple在Python 2中獲得更好的性能(我認為,僅在Python 3的最新版本中,常數集文字才存儲為常數,而不是每次運行函數時重新創建):

if action in {"shut up chip", "go away dude", "screw you", "Java sucks"}:
    # ...

如果您有不相關的測試,那么您可能可以使用anyall函數將它們鏈接在一起,就像使用orand 例如,此代碼將測試與上面相同的字符串,但是將允許任意大寫並在我們要檢查的位旁邊包含額外的文本(它進行子字符串搜索):

if any(phrase in action.lower() for phrase in ("shut up chip", "go away dude",
                                               "screw you", "java sucks")):
    # ...

這是在any調用內使用生成器表達式,這是Python中非常常見的習慣用法(但可能比您學到的要先進一些)。

您可以執行以下操作:

def enter(self):
    print "What's up? Get in the Bran Muffin car!"

    action = raw_input(">  ")

    if(action == "shut up chip" or action == "go away dude" or action == "screw you"):
        print "Screw you!"
        print action
        return next_scene('Your_death')
        #return 'Death' 
    elif action == "hi chip":
        print "What's up loser?!?! Let's go to O&A..."
        return next_scene('Chip_in_studio')
    else:
        print "what's wrong with you? Let's go to my mother's house, I think Lamar's there..."
        return 'Chip_mom_house'

我們在此條件語句中使用or的方式是,值在布爾上下文中從左到右求值,就像使用and 如果任何值為true, or立即返回值。 您可以在包裝所有的括號,其中我們正在評估,看是否每個實例內不同用戶的應對方案的角度來考慮它action有你的用戶輸入值之一。

您可以in字符串元組上使用in運算符。 如果存在匹配項,則返回True

class ChipCar(Scene):
    def enter(self):
        print "What's up? Get in the Bran Muffin car!"

        action = raw_input(">  ")

        if action in ("shut up chip", "go away dude", "screw you"):
            print "Screw you!"
            print action
            return next_scene('Your_death')
            #return 'Death' 
        elif action == "hi chip":
            print "What's up loser?!?! Let's go to O&A..."
            return next_scene('Chip_in_studio')
        else:
            print "what's wrong with you? Let's go to my mother's house, I think Lamar's there..."
            return 'Chip_mom_house'

暫無
暫無

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

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