ldimans
ldimans

Reputation: 19

Sorting list of tuples containing numbers as strings

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

Answers (2)

Eugene Soldatov
Eugene Soldatov

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:

convert decimal mark

Upvotes: 0

sedavidw
sedavidw

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

Related Questions