首页 > 解决方案 > 根据字符串中的降序数值排列列表中的项目

问题描述

  @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",依此类推。

标签: pythonlistdiscorddiscord.py

解决方案


使用一些正则表达式和列表理解应该可以解决问题:

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", ...]

推荐阅读