Home > OS >  How do I sort the second column of this Python output in descending fashion?
How do I sort the second column of this Python output in descending fashion?

Time:07-16

I can't seem to get this code to sort on avg_n_ratings in descending fashion.

Can someone please advise on how to do so, thanks.

genres_ios = freq_table(ios_final, -5)

for genre in genres_ios:
    total = 0
    len_genre = 0
    for app in ios_final:
        genre_app = app[-5]
        if genre_app == genre:            
            n_ratings = float(app[5])
            total  = n_ratings
            len_genre  = 1
    avg_n_ratings = total / len_genre
    print(genre, ':',  avg_n_ratings)

Here are the unsorted results to the code as is.

Results

CodePudding user response:

At the moment you just print your statements one by one, no sorting possible. You need to bunch them together (e.g. to a list) to get a sorting done.

Try this:

genres_ios = freq_table(ios_final, -5)

result = []
for genre in genres_ios:
    total = 0
    len_genre = 0
    for app in ios_final:
        genre_app = app[-5]
        if genre_app == genre:            
            n_ratings = float(app[5])
            total  = n_ratings
            len_genre  = 1
    avg_n_ratings = total / len_genre
    result.append((genre, avg_n_ratings))

sorted_list = sorted(result, key= lambda tup: tup[1])
# the key makes the list be sorted by the 2nd element (which is the number) of each tuple 
print(sorted_list)
  • Related