Home > Software design >  List in order of size
List in order of size

Time:08-02

I'm trying to create a list that prints out the highest number first with a name next to it, like a football table. This is a set of test code that I have been trying it with.

import numpy as np

aa = 5
ab = 3
ac = 8
ad = 6

bb = (aa, ab, ac, ad)

cc = sorted(bb, reverse=True)
splits = np.array_split(cc, 4)

for array in splits:
    print(list(array))

It returns the numbers in a descending pattern like this:

[8]
[6]
[5]
[3]

What I am after looks like:

AC - 8
AD - 6
AA - 5
AB - 3

CodePudding user response:

I think you are looking for somethings such as this:

# You can store elements as list of dictionaries
bb = [{'aa':5},{'ab':3},{'ac':8},{'ad':6}]

# Sorting by value, since key (of each dictionary varies)
cc = sorted(bb, key = lambda x: list(x.values())[0], reverse=True)

# Printing the results
for pair in cc:
    for key, value in pair.items():
        print(key, value)

or similarly using a dictionary:

bb = {'aa': 5, 'ab': 3, 'ac': 8, 'ad': 6}
cc = sorted(bb.items(), key=lambda item: item[1],reverse=True)

for pair in cc:
    print(pair[0],pair[1])

Free to comment below, I will clarify any points of confusion!

  • Related