Doubt with sorted when sorting list of integers in the form of strings

2

I have this list A :

A = ['-1', '-2', '-2', '1', '1', '10', '100', '20', '4']

If I put sorted(A) I get this

['1', '1', '-1', '20', '4', '-2', '-2', '10', '100']

I tried this list:

lista = ['3', '2', '5', '6', '7']

and if I repeat this process, that is to say sorted(lista) , I print it neat but, for some reason, with the negative numbers I have problems. I do not understand why Python no longer orders it properly.

What I needed was for me to organize a list of string numbers, without needing to return them whole and without using a cycle .

Any idea why it happens and if it can be solved?

    
asked by DDR 31.01.2018 в 05:30
source

1 answer

1

Since your list is a list of strings, Python orders them as such using the codepoints unicode. This causes, for example, '103' to be considered less than '3', since '1' is less than '3'.

If you do not want to pass your list to integers, simply use the argument key of sort :

>>> a = ['5', '101', '47', '-4', '-14', '0']
>>> a.sort(key=int)
>>> a
['-14', '-4', '0', '5', '47', '101']

Or with sorted :

>>> a = ['-1', '-2', '-2', '1', '1', '10', '100', '20', '4']
>>> sorted(a, key=int)
['-2', '-2', '-1', '1', '1', '4', '10', '20', '100']

Note that sorted returns a new list, ordered copy of the original, while list.sort orders the original list directly.

    
answered by 31.01.2018 / 08:12
source