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

Python Discord Bot嵌入列表计数异常问题求助

问题解决:Discord Embed列表生成递增序号

错误原因分析

你的代码存在两个关键问题:

  1. 变量名拼写错误:定义的变量是count,但拼接字符串时误用了contar,会直接导致运行报错(未定义变量)。
  2. 逻辑错误:循环中每次都重新对整个data列表执行join操作,且用当前循环的count值作为所有条目的序号,最终所有条目都会显示循环最后一次的count值(也就是列表总长度),无法实现递增序号。

修正后的代码

@bot.command()
async def habbo(ctx):
    response = requests.get("https://images.habbo.com/habbo-web-leaderboards/hhes/visited-rooms/daily/latest.json")
    data = response.json()
    # 使用enumerate直接获取从1开始的递增序号和对应条目
    content = "\n\n".join(f"{index} - {item['name']}" for index, item in enumerate(data, start=1))
    embed = discord.Embed(title="", description=content, color=discord.Colour.random())
    await ctx.send(embed=embed)

代码说明

  • 用enumerate(data, start=1)遍历数据,直接获取从1开始的递增序号index和对应的房间条目item。
  • 对每个条目生成"序号 - 房间名"的字符串,再用\n\n连接所有字符串,得到带递增序号的列表内容。
  • 去掉了多余的循环和计数变量,逻辑更简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:25:22