Reputation: 19
I'm new to programming and I'm not sure how to do this correctly. I'm trying to sort a list of tuples such as below by the second value and I need them to be sorted as if they were ints:
[u'value3', '5,423']
[u'value', '1,389']
[u'value1', '3,385']
[u'anothervalue', '2,789']
[u'value2', '430']
Right now I have this:
sortedList= sorted(listToSort, key=lambda x: (x[1]))
as the result I get this:
[u'value', '1,389']
[u'anothervalue', '2,789']
[u'value1', '3,385']
[u'value2', '430']
[u'value3', '5,423']
but I need it to be more like:
[u'value3', '5,423']
[u'value1', '3,385']
[u'anothervalue', '2,789']
[u'value', '1,389']
[u'value2', '430']
or in ascending order, it doesn't matter. Any help is appreciated.
Upvotes: 0
Views: 894
Reputation: 10145
If your values are integers with comma as thousands delimiter, you should do:
sortedList = sorted(listToSort, key=lambda x: int(x[1].replace(",", "")))
If your values are float:
sortedList = sorted(listToSort, key=lambda x: float(x[1].replace(",", ".")))
Or you can set right locale to not use replace
:
Upvotes: 0
Reputation: 11691
You want the following:
sortedList = sorted(listToSort, key=lambda x: int(x[1].replace(',', '')), reverse=True)
EDIT: original answer did descending, edited to be ascending
Upvotes: 3