TypeError:列表索引必须是整数或片,而不是str、discord和py

2024-06-25 05:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

song_names=[“蒙面狼-海洋中的宇航员”,“比利·艾利斯-坏人”]

async def queue(ctx):
    counter = 1
    print(song_names)
    for str in song_names:
        await ctx.channel.send(counter + song_names[str])
        counter += 1```

This is the error I get:

```  File "E:/.MAIN/Files/Programming/Main/main.py", line 430, in queue
    await ctx.channel.send(counter + song_names[str])
TypeError: list indices must be integers or slices, not str```

Tags: insendasyncnamesqueuesongcounterchannel
2条回答

循环列表时,它通常遍历每个元素。在本例中,您希望获取当前迭代元素的索引。为此,您可以在Python中使用enumerate

语法:

enumerate(iterable, start=0)

完整代码:

async def queue(ctx):
    counter = 1
    print(song_names)
    for index, song_name in enumerate(song_names):
        await ctx.channel.send(counter + song_names[index])
        counter += 1

您已经在迭代项目sp,您可以只使用变量,而不使用str作为变量名:

async def queue(ctx):
    counter = 1
    print(song_names)
    for mystr in song_names:
        await ctx.channel.send(str(counter) + mystr)
        counter += 1

看起来你需要enumerate()

async def queue(ctx):
    print(song_names)
    for index, mystr in enumerate(song_names):
        await ctx.channel.send(str(index+1) + mystr)

相关问题 更多 >