You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化Python中的多分支if-elif语句?以消息统计代码为例

优化Discord机器人消息统计的ID判断逻辑

现有一段基于hikari框架的Discord机器人消息统计代码,通过判断消息发送者的author_id来更新Google Sheet对应单元格的计数:

@bot.listen(hikari.GuildMessageCreateEvent)
async def message_count(event):
    if event.author_id == 2077187399893646:
        wks.update('B3', int(wks.acell('B3').value) + 1)
    elif event.author_id == 5698347053572369:
        wks.update('B4', int(wks.acell('B4').value) + 1)
    elif event.author_id == 495226377080012800:
        wks.update('B5', int(wks.acell('B5').value) + 1)
    elif event.author_id == 4270132384522260:
        wks.update('B6', int(wks.acell('B6').value) + 1)
    elif event.author_id == 9929743815734492:
        wks.update('B7', int(wks.acell('B7').value) + 1)
    elif event.author_id == 10163219484660768:
        wks.update('B8', int(wks.acell('B8').value) + 1)
    elif event.author_id == 9564825465720691:
        wks.update('B9', int(wks.acell('B9').value) + 1)

其中wks.acell(B).value用于读取Google Sheet对应单元格的值,wks.update(A, 值)用于更新指定单元格数值。请问有没有比多分支if-elif更优化的方式来判断author_id?

当然有,用字典映射是更优的方案,不仅代码更简洁,后续新增或修改ID与单元格的对应关系时也更易维护,不用反复修改分支判断逻辑。

优化后的代码示例:

@bot.listen(hikari.GuildMessageCreateEvent)
async def message_count(event):
    # 建立author_id到对应单元格的映射字典
    id_to_cell = {
        2077187399893646: 'B3',
        5698347053572369: 'B4',
        495226377080012800: 'B5',
        4270132384522260: 'B6',
        9929743815734492: 'B7',
        10163219484660768: 'B8',
        9564825465720691: 'B9'
    }
    
    # 检查当前author_id是否在映射中
    cell = id_to_cell.get(event.author_id)
    if cell:
        current_value = int(wks.acell(cell).value)
        wks.update(cell, current_value + 1)

优化点说明

  • 把ID和单元格的对应关系抽离成字典,逻辑更清晰,修改时只需调整字典内容
  • 使用dict.get()方法安全获取对应单元格,避免KeyError,不存在的ID直接跳过
  • 代码行数减少,可读性和可维护性大幅提升

内容的提问来源于stack exchange,提问作者Kitty Summoner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:10:37