Home > OS >  Can you sort a array of strings that containt numbers by value?
Can you sort a array of strings that containt numbers by value?

Time:10-28

I have a array that contains users their names and money. What I am trying to do is to sort the array by money in descending order, so that I can make a leaderboard for who has the most money.

This is my current code:

@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)

And this is the output I get:

The Output

The output I get is alright, the numbers just need to be in descending order. I searched for a solution but couldn't find anything, it feels like an easy fix but I have no idea on what to do.

CodePudding user response:

The best way to do that is to separate your data. You have the name and money in a string. Let's separate them first:

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]]

Now let's sort them by second column (see this):

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

CodePudding user response:

You can use the below function to sort the data,

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

Assuming your data is in this form


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

  • Related