有没有办法删除太多if else条件?

时间:2016-10-02 11:50:02

标签: python

我目前正在使用python制作一个能够理解和回复的交互式系统。因此,为此机器分析和处理有很多条件。例如。请使用以下代码(仅供参考):

    if ('goodbye') in message:                          
        rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0']
        speekmodule.speek(rand,n,mixer)
        break

    if ('hello') in message or ('hi') in message:
        rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.']
        speekmodule.speek(rand,n,mixer)

    if ('thanks') in message or ('tanks') in message or ('thank you') in message:
        rand = ['You are wellcome', 'no problem']
        speekmodule.speek(rand,n,mixer)

    if message == ('jarvis'):
        rand = ['Yes Sir?', 'What can I doo for you sir?']
        speekmodule.speek(rand,n,mixer)

    if  ('how are you') in message or ('and you') in message or ('are you okay') in message:
        rand = ['Fine thank you']
        speekmodule.speek(rand,n,mixer)

    if  ('*') in message:
        rand = ['Be polite please']
        speekmodule.speek(rand,n,mixer)

    if ('your name') in message:
        rand = ['My name is Jarvis, at your service sir']
        speekmodule.speek(rand,n,mixer)

那么,有没有办法可以替换所有这些if else条件?因为有更多的条件,它会使执行速度变慢。

4 个答案:

答案 0 :(得分:2)

制作独家“if”:

docker-compose -f app.yml up

ERROR: for xboard-tomcat  No such image: sha256:34aefb95b68da96e5a5a6cb8b12bb85d926d9d1e5bea2c6c13d1ff9c00d4426d
←[31mERROR←[0m: Encountered errors while bringing up the project.

使用RegEx的映射:

if 'goodbye' in message:                          
    rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0']

elif 'hello' in message or 'hi' in message:
    rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.']

elif 'thanks' in message or 'tanks' in message or ('thank you') in message:
    rand = ['You are wellcome', 'no problem']

elif message == 'jarvis':
    rand = ['Yes Sir?', 'What can I doo for you sir?']

elif  'how are you' in message or 'and you' in message or ('are you okay') in message:
    rand = ['Fine thank you']

elif  '*' in message:
    rand = ['Be polite please']

elif 'your name' in message:
    rand = ['My name is Jarvis, at your service sir']

else:
    raise NotImplementedError("What to do?")

speekmodule.speek(rand, n, mixer)

由你来决定。

答案 1 :(得分:0)

if/elif/else是在Python中构建此类代码的自然方式。正如@imant所指出的,你可以在简单分支的情况下使用基于dict的方法,但我在你的if谓词中看到了一些稍微复杂的逻辑,所以你必须在任何情况下检查所有谓词并且你赢了'使用其他代码结构可以获得任何性能提升。

如果你将你的谓词和行为分解出来,它可能会更容易阅读和维护:

from collections import OrderedDict

def goodbye_p(message):
    return 'goodbye' in message

def goodbye_a():
    rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0']
    # As @Moinuddin Quadri I also assume that your `speek` method
    # says random message from a list.
    # Otherwise you can use `random.choice` method 
    # to get a random message out of a list: `random.choice(messages)`.
    speekmodule.speek(rand, n, mixer)


def hello_p(message):
    return 'hello' in message or 'hi' in message

def hello_a():
    rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.']
    speekmodule.speek(rand, n, mixer)

# Use `OrderedDict` instead of `dict` to control order
# of checks and actions.
branches = OrderedDict([
    # (predicate as key, action as value)
    (goodbye_p, goodbye_a),
    (hello_p, hello_a),
])

for predicate, action in branches.items():
    if predicate(message):
        action_result = action()
        # You can add some logic here based on action results.
        # E.g. you can return some special object from `goodbye_a`
        # and then shut down Jarvis here.
        # Or if your actions are exclusive, you can add `break` here.

如果所有谓词都相同并且只包含子字符串检查,那么将元组(例如('hello', 'hi'))作为dict键可能会更高效。然后你可以迭代这些键:

for words, action in branches.items():
    if any(word in message for word in words):
        action()

答案 2 :(得分:0)

首先使用您想要在dict中匹配的字符串tuple创建一个message对象,并将其与您的Jarvis所假定的值string相关联回复。例如:

jarvis_dict = {
    ('goodbye',)  : ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0'],
    ('hello', 
     'hi')        : ['Wellcome to Jarvis virtual intelligence project. At your service sir.'],
    ('thanks', 
     'tanks', 
     'thank you') : ['You are wellcome', 'no problem'],
    ('jarvis',)   : ['Yes Sir?', 'What can I doo for you sir?'],
    ('how are you', 
     'and you', 
     'are you okay'): ['Fine thank you'],
    ('*',)        : ['Be polite please'],
    ('your name',): ['My name is Jarvis, at your service sir']
}

现在迭代你dict的每个键以检查是否有任何子字符串是消息的一部分,如果有任何匹配,请将speekmodule.speek(rand,n,mixer)函数调用为:

for key, value in jarvis_dict.items():
    if any(item in message for item in key):
        speekmodule.speek(value, n, mixer)

注意:这里我假设代码中的speekmodule.speek(value, n, mixer)正在运行,因为您的代码中没有关于声明的信息。我刚刚将rand替换为value,因为代码中使用的str返回的dict列表相同。

答案 3 :(得分:0)

使用字典:

someCollections = {
    'goodbye': "Something1",
    'hello': "Somthing2",
    ...
}

speekmodule(someCollections [SomeKey],...)
相关问题