How can I sort a list of strings alphabetically first and then numerically in Python?
Eg:
Given list: li = ['4', '1', '3', '9', 'Z', 'P', 'V', 'A']
I want the following output after sorting:
sorted_list = ['A', 'P', 'V', 'Z', '1', '3', '4', '9']
sorted(sorted_list, key=lambda x: (x.isnumeric(),int(x) if x.isnumeric() else x))
this sorts also by value of the integer
You can try this. The desired output can achieved by using str.isdigit
sorted(l,key=lambda x:(x.isdigit(),x))
# ['A', 'P', 'V', 'Z', '1', '3', '4', '9']
NOTE: This solution doesn't handle digits more than one. Please take a look at @Martin's answer.
In case you want it to take in consideration negative numbers, decimals and lower-case letters:
li = ['A', 'b', '-400', '1.3', '10', '42', 'V', 'z']
threshold = abs(min(float(x) for x in li if not x.isalpha())) + ord('z') + 1
sorted_list = sorted(li,
key=lambda x: ord(x) if x.isalpha() else threshold + float(x))
sorted_list
:
['A', 'V', 'b', 'z', '-400', '1.3', '10', '42']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.