【问题标题】:Can you sort a array of strings that containt numbers by value? [duplicate]您可以按值对包含数字的字符串数组进行排序吗? [复制]
【发布时间】:2021-12-13 10:11:25
【问题描述】:

我有一个数组,其中包含用户的姓名和金钱。 我正在尝试做的是按金额按降序对数组进行排序,这样我就可以为谁拥有最多的钱做一个排行榜。

这是我当前的代码:

@client.command()
async def score(ctx):
  channel = ctx.message.channel
  data = loadjson()
  scoreboard = []
  Minimum_money = 0
  for line in data:
    Current_name = line["name"]
    Current_money = line["money"]
    if Current_money > Minimum_money:
      value = Current_name + " " + str(Current_money)
      scoreboard.append(value)
    elif not scoreboard:
      scoreboard.append("Empty!")
    
  return print(scoreboard)

这是我得到的输出:

我得到的输出没问题,数字只需要按降序排列即可。我搜索了解决方案,但找不到任何东西,感觉很容易解决,但我不知道该怎么做。

【问题讨论】:

    标签: python arrays string sorting discord


    【解决方案1】:

    做到这一点的最佳方法是分离您的数据。你有一个字符串中的名字和钱。我们先把它们分开:

    data = ["Mohammad 10", "Yucel 15", "Yusuf 12"]
    data_sep = [[d.split()[0], float(d.split()[1])] for d in data]
    
    print(data_sep) # [['Mohammad', 10.0], ['Yucel', 15.0], ['Yusuf', 12.0]]
    

    现在让我们按第二列对它们进行排序(参见this):

    print(sorted(data_sep, key=lambda l: l[1], reverse=True)) # Toggle reverse to change descending/ascending
    

    【讨论】:

      【解决方案2】:

      您可以使用以下函数对数据进行排序,

      def quicksort(data):
          left = []
          right = []
          ref = [data[int(len(data)/2)]]
          
      
          for line in data:
              if line == ref[0]:
                  continue
              if line["money"] < ref[0]["money"]:
                  right.append(line)
              else:
                  left.append(line)
          
          if left != []:
              left = quicksort(left)
          if right != []:
              right = quicksort(right)
      
          sorted_data = left + ref + right
      
          return sorted_data
      

      假设你的数据是这种形式

      
          data = [{"name":"himanshu", "money":25}, {"name":"aniket", "money":34}, {"name":"ani", "money":3}]
      
      

      【讨论】:

        猜你喜欢
        • 2011-07-23
        • 2020-02-18
        • 2019-05-26
        • 2011-03-07
        • 1970-01-01
        • 2014-08-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多