I'm trying to sort a list of unknown values, either ints or floats or both, in ascending order. i.e, [2,-1,1.0] would become [-1,1.0,2]. Unfortunately, the sorted() function doesn't seem to work as it seems to sort in descending order by absolute value. Any ideas?
Asked
Active
Viewed 6,221 times
2
-
[`sorted([2,-1,1.0])` yields `[-1, 1.0, 2]`](http://ideone.com/j0937A). What is your question? – johnsyweb Feb 24 '13 at 01:28
2 Answers
2
I had the same problem. The answer: Python will sort numbers by the absolute value if you have them as strings. So as your key, make sure to include an int() or float() argument. My working syntax was
data = sorted(data, key = lambda x: float(x[0]))
...the lambda x part just gives a function which outputs the thing you want to sort by. So it takes in a row in my list, finds the float 0th element, and sorts by that.

doublefelix
- 952
- 1
- 9
- 22
-
To expand on your answer, the difference between `2` and `'2'` is that one is an integer and the other is a string. The fact that the string contains digits doesn't change the way it's sorted because strings are sorted lexicographically (like in a dictionary), so `'-2' < '-5'` (because `'-' == '-'` and `'2' < '5'`). Integers, on the other hand, are sorted by value. – Blender May 05 '17 at 02:37
0
In addition to doublefelix,below code gives the absolute order to me from string.
siparis=sorted(siparis, key=lambda sublist:abs(float(sublist[1])))

sinan
- 31
- 3