Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting tuple based on int column in python

I have the following tuple:

['Southampton', '9', '14', '13']
['Nottingham Forest', '8', '10', '17']
['Coventry City', '7', '4', '14']
['Blackburn Rovers', '4', '6', '14']
['Newcastle United', '24', '20', '10']
['FC Wimbledon', '21', '20', '11']
['Arsenal', '21', '19', '8']

And i want to sort it by the 2nd and 3rd column. So i use the following code:

sorted_rank = sorted(temp_rank, key=itemgetter(1,2), reverse=True)

But as you can see the 2nd and 3rd column is not int, so the sorting process finished wrong. How can i "tell" to python that these columns are int and not string?

I tried this but nothing:

sorted_rank = sorted(temp_rank, key=itemgetter(1,int(2)), reverse=True)
like image 463
zuperakos Avatar asked Jan 21 '26 11:01

zuperakos


2 Answers

You have to specify a custom function or lambda instead.

The following works:

sorted_rank = sorted(temp_rank, key=lambda i: (int(i[1]), int(i[2])), reverse=True)

where sorted_rank becomes:

[['Newcastle United', '24', '20', '10'],
 ['FC Wimbledon', '21', '20', '11'],
 ['Arsenal', '21', '19', '8'],
 ['Southampton', '9', '14', '13'],
 ['Nottingham Forest', '8', '10', '17'],
 ['Coventry City', '7', '4', '14'],
 ['Blackburn Rovers', '4', '6', '14']]
like image 71
Martijn Pieters Avatar answered Jan 22 '26 23:01

Martijn Pieters


def key_fct(tup):
    return (int(tup[1]), int(tup[2]))

sorted_rank = sorted(temp_rank, key=key_fct, reverse=True)
like image 30
dugres Avatar answered Jan 22 '26 23:01

dugres



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!