根据字符串中的降序数值排列列表中的项目

Posted

技术标签:

【中文标题】根据字符串中的降序数值排列列表中的项目【英文标题】:Arranging items in list according to descending numerical value in a string 【发布时间】:2021-09-03 19:45:50 【问题描述】:
  @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",依此类推。

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于根据字符串中的降序数值排列列表中的项目的主要内容,如果未能解决你的问题,请参考以下文章

如何按第一位数字的降序对整数数组进行排序? [关闭]

实现数组的降序排列

按特定键的降序对字典列表进行排序[重复]

转<<C#集合Dictionary中按值的降序排列

如何实现JSP列表升序或者降序

如何按数字向量的降序显示ggplot2中的条形?