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

如何在Python(discord.py)的IF语句中返回多个目标字典值?

问题描述

尝试遍历JSON字典中的所有值,获取生日为指定日期的用户,但目前仅能返回第一个匹配值。引用的JSON字典如下:

{
    "TARGETGUILD": {
        "USERID1": {
            "month": "09",
            "day": "10"
        },
        "USERID2": {
            "month": "09",
            "day": "10"
        }
    },
    "otherGUILD": {
        "USERID": {
            "month": "09",
            "day": "10"
        }
    }
}

当前使用的Python代码(Discord.py命令):

@commands.command(name="today", pass_context=True)
async def today(self, ctx):
    today = datetime.today()
    today_month = today.strftime("%m")
    today_day = today.strftime("%d")
    guild_av = ctx.guild.icon_url

    with open('commands/birthday/birthdays.json', 'r') as f:
        data = json.load(f)
    guild_data = data[str(ctx.guild.id)]
    birthday_dict = {"month": str(today_month), "day": str(today_day)}
    #length = len(guild_data)
    def find_birthday():
        for user in guild_data:
            if guild_data[user] == birthday_dict:
                return ":tada: <@!" + str(user) + ">" + "\n"
            else:
                return "`None`"

    embed = discord.Embed(title=f":calendar_spiral: {today_month}/{today_day}", description="**Today's Birthdays:**" + "\n" + "\n" + str(find_birthday()), color=discord.Color.greyple())
    embed.set_thumbnail(url=guild_av)
    await ctx.send(embed=embed)

问题表现:仅显示第一个匹配用户,只有单个匹配用户的服务器能正常工作。测试发现遍历能打印所有用户,问题出在IF语句中,仅返回第一个匹配用户,需要改写代码让其返回多个匹配值。

问题原因

原代码中的find_birthday函数存在逻辑错误:

  • 循环第一次迭代时,只要遇到用户就直接return,不管后续还有没有其他匹配用户
  • 如果第一个用户生日不匹配,直接返回"None",完全跳过了对其他用户的检查
修改方案

需要先收集所有符合条件的用户,再生成结果字符串,而不是找到第一个就返回。具体步骤:

  1. 初始化一个空列表,用于存储匹配的用户消息
  2. 遍历所有用户,将符合生日条件的用户ID格式化为指定字符串后加入列表
  3. 遍历结束后,根据列表是否为空生成最终描述内容:
    • 列表不为空:将所有用户消息拼接成字符串
    • 列表为空:返回"None"
修改后的代码
@commands.command(name="today", pass_context=True)
async def today(self, ctx):
    today = datetime.today()
    today_month = today.strftime("%m")
    today_day = today.strftime("%d")
    guild_av = ctx.guild.icon_url

    with open('commands/birthday/birthdays.json', 'r') as f:
        data = json.load(f)
    guild_data = data[str(ctx.guild.id)]
    birthday_dict = {"month": today_month, "day": today_day}

    # 收集所有匹配的生日用户
    birthday_users = []
    for user_id, birthday_info in guild_data.items():
        if birthday_info == birthday_dict:
            birthday_users.append(f":tada: <@!{user_id}>")
    
    # 生成描述内容
    if birthday_users:
        birthday_text = "\n".join(birthday_users)
    else:
        birthday_text = "`None`"

    embed = discord.Embed(
        title=f":calendar_spiral: {today_month}/{today_day}",
        description=f"**Today's Birthdays:**\n\n{birthday_text}",
        color=discord.Color.greyple()
    )
    embed.set_thumbnail(url=guild_av)
    await ctx.send(embed=embed)
额外优化点
  • 使用guild_data.items()直接遍历键值对,代码更简洁易读
  • 去掉了不必要的str()转换(today_month和today_day本身就是字符串)
  • 使用f-string格式化用户消息,比字符串拼接更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:30:42