python-3.x - 使具有许多“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
解决方案
您不必尝试每一对True
和False
组合,您可以根据每个单独的条件逐步构建结果:
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
推荐阅读
- mongodb - MongoDB 仅查找某些值
- javascript - 每周在 ReactJS 中从 Firebase 中清除价值
- vue.js - Vue单元测试: beforeEach() 在所有测试之后执行,而不是在每个测试之前执行
- javascript - JQuery 触发器导致我的 React 组件消失
- pine-script - plotcandle 和 plotbar 不支持像 plot 和 plotchar 这样的“偏移”参数
- google-cloud-platform - GCP 日志指标资源管理器问题
- typescript - typeorm:如何将一列的默认值设置为依赖于 id 列?
- makefile - makefile.unix:188: obj/magirpc.o 编译时出现错误 1
- sql - postgres sql如何将所有序列重置为1
- yaml - 如何使用 pandoc 使用 YAML 元数据值填充 docx 占位符?