0

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.

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by bharatk
1

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

Edited by Gribouillis: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.