如何根据给定的要求自动拆分列表? [英] How can I automatically split a list up based on a given requirement?
问题描述
在Discord上,您只能接收字符长度为2000或以下的消息.我试图将僵尸程序所在的每个服务器的服务器名称,成员数量和服务器ID附加到列表中,然后将该列表发送到频道.
On Discord, you can only have messages of character length 2000 or under. I am trying to append the server name, member amount and server ID for each server that the bot is in to a list, and then sending the list to a channel.
但是,当列表长度超过2000时,我试图将其拆分,但是该方法要求每次列表变大时都必须手动对其进行更新.如何使脚本根据需要的分割数"自动分割列表,然后发送这些分割数"?
However, as the list length exceeds 2000 I have tried to split it up, however the method requires it to be updated every time manually as the list gets larger. How can I make the script automatically split up the list based on how many 'splits' are required and then send those 'splits'?
到目前为止,我可以运行,但是不是自动的:
What I have so far, which works, but is not automatic:
@commands.command()
async def getallservers(self, ctx):
serverslist = []
def split_list(alist, wanted_parts=1):
length = len(alist)
return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
for i in range(wanted_parts) ]
if ctx.author.id == 204616460797083648:
for x in self.bot.guilds:
serverslist.append(f'{x.name}: **{len(x.members)}** - {x.id}\n')
q1,q2,q3,q4,q5,q6 = split_list(serverslist, wanted_parts=6)
embed = discord.Embed(title='Server List')
embed.description = ''.join(q1)
await ctx.send(embed=embed)
embed.description = ''.join(q2)
await ctx.send(embed=embed)
embed.description = ''.join(q3)
await ctx.send(embed=embed)
embed.description = ''.join(q4)
await ctx.send(embed=embed)
embed.description = ''.join(q5)
await ctx.send(embed=embed)
embed.description = ''.join(q6)
await ctx.send(embed=embed)
else:
pass
推荐答案
一个拥有 serverslist
的人,可以将其传递给构建<2000个字符页面
One you have the serverslist
, you can pass it to a function that builds < 2000 character pages
def paginate(lines, chars=2000):
size = 0
message = []
for line in lines:
if len(line) + size > chars:
yield message
message = []
size = 0
message.append(line)
size += len(line)
yield message
然后在您的命令中
for message in paginate(serverlist):
embed.description = ''.join(message)
await ctx.send(embed=embed)
这篇关于如何根据给定的要求自动拆分列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!