首页 > 解决方案 > 使具有许多“ifs”的 Python 代码更高效

问题描述

我正在为“Telegram Bot”类编写方法,其中一种方法是带有 3 个可选参数的“getUpdate” —— “last_message”、“chat_id”和“text”。 如果您注意提供的代码,您将能够看到它包含 5 个 ifs 语句。我相信应该有办法减少它的数量。

Json 文件看起来下一个方式:

{'ok': True, 'result': [{'update_id': xxxxx, 'message': {'message_id': 2, 'from': {'id': xxxxx, 'is_bot': False, 'first_name' : 'Xxxx', 'last_name': 'Xxxx', 'language_code': 'en'}, 'chat': {'id': xxxxxxx, 'first_name': 'Xxxx', 'last_name': 'Xxxx', ' type': 'private'}, 'date': 1560346414, 'text': 'Hi'}}, {'update_id': xxxxxx, 'message': {'message_id': 3, 'from': {'id' : xxxxx, 'is_bot': False, 'first_name': 'xxxx'}, 'chat': {'id': xxxx, 'first_name': 'Zzzz', 'type': 'private'}, 'date': 1560346988, '文本': '/开始', '实体': [{'offset': 0, 'length': 6, 'type': 'bot_command'}]}}, {'update_id': xzcdsfsdcd, 'message': {'message_id': 4, 'from' : {'id': xxxx, 'is_bot': False, 'first_name': 'xxxxx', 'language_code': 'ru'}, 'chat': {'id': xxxx, 'first_name': 'Zzzz', 'type': 'private'}, 'date': 1560346990, 'text': 'Hi'}}, {'update_id': xxxxxx, 'message': {'message_id': 22, 'from': {'id ': yyyy, 'is_bot': False, 'first_name': 'Xxxx', 'last_name': 'Xxxx', 'language_code': 'en'}, 'chat': {'id': yyyy, 'first_name': 'Xxxx', '姓氏': 'Xxxx','类型':'私人'},'日期':1560363527,'文本':'嘿'}}]}

def getUpdates(self,last_message=False,chat_id=False,text=False):
    getUpdate_object=requests.get(self.base_url+"getUpdates").json()
    if last_message==True:
        last_message_object=getUpdate_object['result'][len(getUpdate_object['result'])-1]
        if chat_id==False and text==False:
            return last_message_object
        elif chat_id==True and text==False:
            return last_message_object['message']['chat']['id']
        elif chat_id==False and text==True:
            return last_message_object['message']['text']
        elif chat_id==True and text==True:
            chatid=last_message_object['message']['chat']['id']
            last_text=last_message_object['message']['text']
            return (chatid,last_text)
    else:
        return getUpdate_object

标签: python-3.x

解决方案


您不必尝试每一对TrueFalse组合,您可以根据每个单独的条件逐步构建结果:

def getUpdates(self,last_message=False,chat_id=False,text=False):
    getUpdate_object=requests.get(self.base_url+"getUpdates").json()
    if last_message==True:
        last_message_object=getUpdate_object['result'][len(getUpdate_object['result'])-1]
        if not chat_id and not text:
            return last_message_object
        result = []
        if chat_id:
            result.append(last_message_object['message']['chat']['id'])
        if text:
            result.append(last_message_object['message']['text'])
        return tuple(result)
    else:
        return getUpdate_object

推荐阅读