-3

I am trying to sort the following data in a CSV file:

list_all = ["10","2","113.2","200"]

Sounds simple, right? So I use the following codes to sort it:

list_all = ["10","2","113.2","200"]
sortedlist = sorted(list_all)
print(sortedlist)

But it doesn't work properly.

This is the output from my function.

['10', '113.2', '2', '200']

Apparently, it is sorted by the first word in each string only, which is weird. How to solve this?

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
Python NWB
  • 53
  • 5
  • 3
    Why is that weird? – Daniel Roseman Apr 13 '19 at 15:24
  • hint: is there a way to tell sorted to use the float representation of each? – gold_cy Apr 13 '19 at 15:25
  • @PythonNWB It definitely isn't a bug. Try sorting a list with the floating point values instead of string values, and see what happens for yourself. – Jordan Singer Apr 13 '19 at 15:28
  • That's how lexicographic sorting works, it's not a bug in `sorted()`. – Szymon Maszke Apr 13 '19 at 15:28
  • sortedlist = sorted(list_all, key=lambda row: float(row)) This works for CSV file. For any of you experiencing this issue, it mainly arises from the string type of the data in CSV file. Therefore, by converting the type from to , the problem is solved. Thank you for everyone's contribution below! – – Python NWB Apr 13 '19 at 22:44

5 Answers5

1

The elements in that lists are strings, so they are sorted lexicographically. If you want to sort them by their numeric values, you could use a custom sorting key:

sorted(list_all, key = lambda x : float(x))

EDIT:
As aws_apprentice commented, you could just pass a function as the sorting key and make this call a bit more concise:

sorted(list_all, key = float)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You are trying to sort str types, not int or float.

>>> list_all = [10,2,113.2,200]
>>> sortedlist = sorted(list_all)
>>> print(sortedlist)
[2, 10, 113.2, 200]
Rasgel
  • 152
  • 1
  • 1
  • 13
0

Try this:

list_all = ["10","2","113.2","200"]
list_all.sort(key = float) 
print(list_all)
Henrique
  • 328
  • 1
  • 2
  • 10
  • this sorts the list in place, is that what OP wants? also doesn't hurt to include an explanation – gold_cy Apr 13 '19 at 15:31
0

It's because its sorting its contents like strings (because that's what they are), you could sort them to by their float representation using sorted argument key.

list_all = ["10","2","113.2","200"]
sortedlist = sorted(list_all, key=float)

print(sortedlist) # --> ['2', '10', '113.2', '200']
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
-1

Python interprets anything inside quotations ' or double quotations " as the String type. So the numbers you have written are not numbers, are just words!

sorted()

on strings then, works according to the characters. Just remove the quotations:

list_all = [10,2,113.2,200]
S. Ali Mirferdos
  • 192
  • 1
  • 2
  • 12