I know that this sounds trivial but I did not realize that the sort()
function of Python was weird. I have a list of \"numbers\" that are actually in string for
You could pass a function to the key
parameter to the .sort method. With this, the system will sort by key(x) instead of x.
list1.sort(key=int)
BTW, to convert the list to integers permanently, use the map function
list1 = list(map(int, list1)) # you don't need to call list() in Python 2.x
or list comprehension
list1 = [int(x) for x in list1]
may be not the best python, but for string lists like ['1','1.0','2.0','2', '1.1', '1.10', '1.11', '1.2','7','3','5']with the expected target ['1', '1.0', '1.1', '1.2', '1.10', '1.11', '2', '2.0', '3', '5', '7'] helped me...
unsortedList = ['1','1.0','2.0','2', '1.1', '1.10', '1.11', '1.2','7','3','5']
sortedList = []
sortDict = {}
sortVal = []
#set zero correct (integer): examp: 1.000 will be 1 and breaks the order
zero = "000"
for i in sorted(unsortedList):
x = i.split(".")
if x[0] in sortDict:
if len(x) > 1:
sortVal.append(x[1])
else:
sortVal.append(zero)
sortDict[x[0]] = sorted(sortVal, key = int)
else:
sortVal = []
if len(x) > 1:
sortVal.append(x[1])
else:
sortVal.append(zero)
sortDict[x[0]] = sortVal
for key in sortDict:
for val in sortDict[key]:
if val == zero:
sortedList.append(str(key))
else:
sortedList.append(str(key) + "." + str(val))
print(sortedList)
You haven't actually converted your strings to ints. Or rather, you did, but then you didn't do anything with the results. What you want is:
list1 = ["1","10","3","22","23","4","2","200"]
list1 = [int(x) for x in list1]
list1.sort()
If for some reason you need to keep strings instead of ints (usually a bad idea, but maybe you need to preserve leading zeros or something), you can use a key function. sort
takes a named parameter, key
, which is a function that is called on each element before it is compared. The key function's return values are compared instead of comparing the list elements directly:
list1 = ["1","10","3","22","23","4","2","200"]
# call int(x) on each element before comparing it
list1.sort(key=int)
scores = ['91','89','87','86','85']
scores.sort()
print (scores)
This worked for me using python version 3, though it didn't in version 2.
I approached the same problem yesterday and found a module called [natsort][1], which solves your problem. Use:
from natsort import natsorted # pip install natsort
# Example list of strings
a = ['1', '10', '2', '3', '11']
[In] sorted(a)
[Out] ['1', '10', '11', '2', '3']
[In] natsorted(a)
[Out] ['1', '2', '3', '10', '11']
# Your array may contain strings
[In] natsorted(['string11', 'string3', 'string1', 'string10', 'string100'])
[Out] ['string1', 'string3', 'string10', 'string11', 'string100']
It also works for dictionaries as an equivalent of sorted
.
[1]: https://pypi.org/project/natsort/
In case you want to use sorted() function: sorted(list1, key=int)
It returns a new sorted list.