How to Sort Python List of Strings of Numbers

How to sort python list of strings of numbers

You want to sort based on the float values (not string values), so try:

>>> b = ["949.0","1099.0"]
>>> b.sort(key=float)
>>> b
['949.0', '1099.0']

Python: Sort a list of strings composed of letters and numbers

l = ['H1', 'H100', 'H10', 'H3', 'H2', 'H6', 'H11', 'H50', 'H5', 'H99', 'H8']
print sorted(l, key=lambda x: int("".join([i for i in x if i.isdigit()])))

Output:

['H1', 'H2', 'H3', 'H5', 'H6', 'H8', 'H10', 'H11', 'H50', 'H99', 'H100']

How to sort a list of integers that are stored as string in python

We have to use the lambda as a key and make each string to int before the sorted function happens.

sorted(a,key=lambda i: int(i))

Output :
['1', '2', '3', '4', '5', '10']

More shorter way -> sorted(a,key=int). Thanks to @Mark for commenting.

Sorting a list of strings numerically

Yes:

flist.sort(key=lambda fname: int(fname.split('.')[0]))

Explanation: strings are lexically sorted so "10" comes before "3" (because "1" < "3", so whatever comes after "1" in the first string is ignored). So we use list.sort()'s key argument which is a callback function that takes a list item and return the value to be used for ordering for this item - in your case, an integer built from the first part of the filename. This way the list is properly sorted on the numerical values.

How to sort a list of strings numerically?

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)
# or if you want to do it all in the same line
list1 = sorted([int(x) for x in list1])

How do you sort a list of numbers which are strings in python?

Try this:

list = ['1008', '1033', '1080', '3107', '3589', '574', '703', '704', '712', '731', '810', '857', '862', '909', '927', '980']

for i in range(0, len(list)):
list[i] = int(list[i])

list.sort(reverse = True)
print(list)

'''


Related Topics



Leave a reply



Submit