How can I sort a list that contains string numbers and letters in such a way that sorts numbers numerically and then letters alphabetically?
my_list = ["10","2","1","5","a","b","c"]
disable_sorted_list
"1","2","5","10","a","b","c"
How can I sort a list that contains string numbers and letters in such a way that sorts numbers numerically and then letters alphabetically?
my_list = ["10","2","1","5","a","b","c"]
disable_sorted_list
"1","2","5","10","a","b","c"
Sort with an appropriate key function:
>>> sorted(my_list, key=lambda s: (not s.isdigit(), int(s) if s.isdigit() else s))
['1', '2', '5', '10', 'a', 'b', 'c']
The sorting key (not s.isdigit(), int(s) if s.isdigit() else s)
is a pair (tuple)
(bool, str|int)
Since tuples are sorted lexicographically (compare element-wise, decide on first not-equal element), the numbers come first (False < True
).
We convert the numbers to integers in the sorting key so they are not sorted alphabetically
3 < 10 # but
"10" < "3"
Here is a solution (not optimized but easy to understand) :
my_list = ["10","2","1","5","a","b","c"]
int_list = [];
str_list = [];
final_list = [];
# separate integers and string in two different arrays
for element in my_list:
if(element.isdigit()):
int_list.append(int(element))
else:
str_list.append(element)
# sort integers array and strings array
int_list.sort()
str_list.sort()
# cast the integers list into strings list
int_list = list(map(str, int_list))
# add both list to the final list.
final_list = int_list + str_list
print(final_list)