0

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.

ldimans
  • 19
  • 2

2 Answers2

3

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

sedavidw
  • 11,116
  • 13
  • 61
  • 95
0

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

Community
  • 1
  • 1
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
  • 1
    you cant just do this because of the commas. you can do `float(x[1].replace(',','') to get rid of commas – R Nar Oct 22 '15 at 17:40
  • 1
    also, sorted has a 4th parameter `reverse` which can be set so it sorts in reverse order. – R Nar Oct 22 '15 at 17:41
  • Sorry, I missed that there are commas in values. – Eugene Soldatov Oct 22 '15 at 17:42
  • i think you meant to replace with blanks, not periods. that would give decimal values for large values, and `ValueError` if the value has more than one comma (ie, `1,000,000`) – R Nar Oct 22 '15 at 17:43
  • 1
    @RNar Well, for [some people](https://docs.oracle.com/cd/E19455-01/806-0169/overview-9/index.html) it makes sense to consider the comma as the decimal mark. – 301_Moved_Permanently Oct 22 '15 at 17:49
  • this is true, but look at the question, it seems it should be taken in as a blank instead as the OP seems to want to organize from largest to smallest and the bigger numbers have the commas. but yes, i see what you mean – R Nar Oct 22 '15 at 17:51