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)
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']]
def key_fct(tup):
return (int(tup[1]), int(tup[2]))
sorted_rank = sorted(temp_rank, key=key_fct, reverse=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With