Home > other >  Sorting output over multiple lines Python
Sorting output over multiple lines Python

Time:07-18

I have following output, with each number being on their own line.

reaction  2 
reaction  1 
reaction  1 
reaction  2 
reaction  3

How can I sort the numbers in this output to descend from the biggest to the smallest value

reaction  3 
reaction  2 
reaction  2 
reaction  1 
reaction  1 

I got this output with this code. Its a script for a discord bot, that get all messages that have a reaction, checks if its the reaction you were looking for (msgSplit[1]) and checks if its has the amount of reactions you were looking for with if num >= int(msgSplit[2]):

for reaction in historical_message.reactions:
    if reaction.emoji == msgSplit[1]:
        num = reaction.count
        if num >= int(msgSplit[2]):
            print(reaction, num)

CodePudding user response:

I recommend that you store the output on the list as a list of tuples and sort the output in descending order.

output = [] # create empty list
for reaction in historical_message.reactions:
    if reaction.emoji == msgSplit[1]:
        num = reaction.count
        if num >= int(msgSplit[2]):
            # append the the output to the list as tuple
            output.append((reaction, num))
            

print(sorted(output, reverse=True))

CodePudding user response:

There most sensible solution is to save them to a list and then sort the list, but not all sorting algorithms are made equally. If time efficiency is not really an issue and it just has to give the desired output then "bubble sort" is probably the easiest and most intuitive to implement, but its time complexity is O(n^2) which is bad.

"Heapsort" ensures the result will be O(nlogn) in time and O(1) in time which is nice.

See this cheat sheet to decide what is most appropriate for your purposes: https://duckduckgo.com/?q=sorting algorithms cheat sheet&t=brave&iax=images&ia=images&iai=https://cdn-images-1.medium.com/max/2000/1*Ggl_e8v-IzxUdienwrTMZQ.png

CodePudding user response:

You can use sort list method in python and tell it to use the last "column" as the key to order.

def last_col(line):
    return int(l.split()[-1])

text = """reaction  2 
reaction  1 
reaction  1 
reaction  2 
reaction  3
reaction  11
reaction  342384324"""

lines = text.split('\n')

lines.sort(reverse=True, key=last_col)

print(lines)
# ['reaction  342384324', 'reaction  11', 'reaction  3', 'reaction  2 ', 'reaction  2 ', 'reaction  1 ', 'reaction  1 ']
  • Related