python - 根据字符串中的降序数值排列列表中的项目
问题描述
@lastfm.command(name="whoknows",aliases=['wk'],help="Who plays the artist most in a guild")
async def lastfm_whoknows(self,ctx:Context,*,artist:str=None):
wk = []
db = self.db["lastfm"]["lastfm"]
to_find = {"m_id":ctx.author.id}
found = db.find(to_find)
for z in found:
async with aiohttp.ClientSession() as session:
params= {"api_key" : "ok",
"user" : z["username"],
"period" : "overall",
"limit" : 1,
"method":"user.getRecentTracks",
"format":"json"}
async with session.get(url="http://ws.audioscrobbler.com/2.0", params=params) as response:
resp = await response.read()
jsonData1 = json.loads(resp)
for xy in ctx.guild.members:
db = self.db["lastfm"]["lastfm"]
to_find = {"m_id":xy.id}
found = db.find(to_find)
for x in found:
async with aiohttp.ClientSession() as session:
params= {"api_key" : "ok",
"user" : x["username"],
"artist" : jsonData1["recenttracks"]["track"][0]['artist']['#text'],
"method":"artist.getInfo",
"format":"json"}
async with session.get(url="http://ws.audioscrobbler.com/2.0", params=params) as response:
resp = await response.read()
jsonData = json.loads(resp)
alr = f'**{xy.name}** | **{jsonData["artist"]["stats"]["userplaycount"]}**'
wk.append(alr)
join = "\n".join(str(a) for a in wk)
em = discord.Embed(description=join,color=0xec1c24)
await ctx.reply(embed=em, mention_author=False)
所以基本上,我正在尝试创建一个命令,该命令也根据 str 中的数值从列表中输出。例如,list = ["this is 10","this is 200","this is 30"]
它将首先打印出来"this is 200"
,因为它是最高的数字"this is 30"
,依此类推。
解决方案
使用一些正则表达式和列表理解应该可以解决问题:
import re
raw_data = ["this is 10", "this is 200", "this is 30"]
data = [(elem, int(re.match("this is (\d+)", elem).group(1))) for elem in raw_data]
# data = [("this is 10", 10), ("this is 200", 200), ...]
sorted_data = sorted(data, key=lambda x: x[1], reverse=True)
# sorted_data = [("this is 200", 200), ("this is 30", 30), ...]
sorted_raw_data = [elem[0] for elem in sorted_data]
# sorted_raw_data = ["this is 200", "this is 30", ...]
推荐阅读
- python - 根据符号变化创建列表
- django - 有没有办法获取用户上次注销时间 Django 示例 user.last_logout (是否存在这样的事情)
- r - R通过坐标函数内的变量名调用数据框(sp包的)
- json - 作为 Circe-Json 的一部分,如何使用 Hcursor 或 Optics 返回匹配对象列表?
- scala - 在 play framework 中设置 Activator
- json - 使用 Go 进行 JSON 解码失败
- php - Laravel Collections:多维数组,按键和唯一值分组
- android - 如何使用 REST API 创建文件选择器以将文件保存到 Google Drive?
- ffmpeg - 在使用 FFMPEG 为多比特率 VOD 创建多个再现后创建主播放列表
- android - 从适配器发送数据到下一个 Fragment