Hello

I have created a multidimensional list in python

I used the following code:

r =[(300, 4), (5, 6), (100, 2)]

I tried sorting it in ascending order using r.sort()
and I get [(5, 6), (100, 2), (300, 4)]

I want it to get sorted based on each on the 2nd element instead of the first. That is the result should be [(100,2), (300,4), (5,6)]

How do I go about doing this?

Thank you.

Recommended Answers

All 2 Replies

Use the 'key' argument of the 'sort' method like this

def score(item): # define a score function for your list items
    return item[1]

r =[(300, 4), (5, 6), (100, 2)]
r.sort(key = score) # sort by ascending score
print r
"""
my output -->
[(100, 2), (300, 4), (5, 6)]
"""

Thank you, it works. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.