Python: sorting string numbers not lexicographically

I have an array of string-numbers, like:

numbers = ['10', '8', '918', '101010']

When I use sorted(numbers), I get them sorted lexicographically, e.g. '8' > '17'.

How can I iterate over the strings sorted according to the number value?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use the built-in sorted() function with a key int to map each item in your list to an integer prior to comparison:

numbers = ['10', '8', '918', '101010']
numbers = sorted(numbers, key=int)
print(numbers)

Output

['8', '10', '918', '101010']

Using this method will output a list of strings as desired.

Method 2

You can transform the elements of the array to integers by using the built-in map function.

print sorted(map(int, numbers))

Output:

[8, 10, 918, 101010]

Method 3

If you want to keep as strings you can pass int as the key to list.sort which will sort the original list:

numbers = ['10', '8', '918', '101010']
numbers.sort(key=int)

Method 4

Here is how I like to do it, which is very fast.

print(sorted(sorted(numbers), key=len))

Method 5

all elements types are string,

 >>> x=['4', '5', '29', '54', '4', '0', '-214', '542', '-64', '1', '-3', '6', '-6']
 >>> max(x)
 '6'

It “orders” the words alphabetically and returns the one that is at the bottom of the alphabetic list

Few more examples:

    >>> list1 = ['kyle', 'dhamu']
    >>> max(list1)
    'kyle'

returns kyle because k is after d

Also remember from python3.7 you cannot mix strings and integers to use max function. Below is the example

>>> mix_list = ['my', 'name', 'is', 1 ]
>>> max(mix_list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'int' and 'str'


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x