gpt4 book ai didi

python - 我可以在排序列表时使 python 代码工作吗

转载 作者:行者123 更新时间:2023-12-04 13:24:56 25 4
gpt4 key购买 nike

我在 discord.py 上做了一个 top 命令(使用 Replit 数据库)。基本上显示了服务器中 XP 最多的前 10 个用户。
这就是我的代码的一部分的样子,忽略我将 key 保存到数据库的凌乱方式

@commands.command()
async def top(self,ctx,nr:int=1):
match_keys = db.prefix(f"{ctx.guild.id}XP")
sort = sorted(match_keys, key=lambda x: db[x],reverse=True)
[...]
我有 2000 把 key 来排序 ,整个过程大约需要 10 秒钟才能完成。在这 10 秒内,机器人无法使用。我已经测试过了,唯一需要时间的就是排序。我在 StackOverflow 上看到了其他类似的问题,但从我在那里发现的内容来看,排序/排序方法基于快速排序,我真的不能做太多事情来加快速度。
我正在考虑制作一个任务循环,它会不时更新顶部(运行 .top 命令时等待的时间更少),但是机器人在对列表进行排序时将无法使用。
是否可以减慢排序速度,以便我可以在操作时使用机器人?谢谢!
抱歉潜在的错误,我是 stackoverflow 的新手

最佳答案

正如我从评论中了解到的,您的数据库不支持多键/批量查询。但是,您仍然可以采取一些方法,例如 caching , awaitable remote procedures ,转储整个数据库等。
一个快速的解决方案可能是将查询数据库与排序条目分开,使您可以使用异步函数 - 而不是阻止整个十秒。

async def get_entries(match_keys):
entries = {}
for key in match_keys:
entries[key] = db[key]
await asyncio.sleep(0) # yield control to the event loop
return entries
@commands.command()
async def top(self, ctx, nr:int=1):
match_keys = db.prefix(f"{ctx.guild.id}XP")
entries = await get_entries(match_keys)
sort = sorted(entries.items(), key=lambda e: e[1], reverse=True)

关于python - 我可以在排序列表时使 python 代码工作吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69035159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com