I want to sort a list that look like this: ['3', '6', 'B', '2', '1', 'C', 'A']
to something like this: ['1', 'A', '2', 'B', '3', 'C', '6']
.
Thanks in advance!
I want to sort a list that look like this: ['3', '6', 'B', '2', '1', 'C', 'A']
to something like this: ['1', 'A', '2', 'B', '3', 'C', '6']
.
Thanks in advance!
You can try this.
l=['3', '6', 'B', '2', '1', 'C', 'A']
sorted(['3', '6', 'B', '2', 'A', 'C', '1'],key=lambda x:(int(x),0) if x.isnumeric() else ((ord(x)-64)%26,1))
# ['1', 'A', '2', 'B', '3', 'C', '6']
Since numbers are given more priority I made (int(x),0)
for number and for alphabets ((ord(x)-64)%26,1)
for tie-breaking.
from itertools import zip_longest
l = ['3', '6', 'B', '2', '1', 'C', 'A']
num = sorted(filter(str.isnumeric, l), key=lambda x: int(x))
ch = sorted(filter(str.isalpha, l))
[ e for t in zip_longest(num, ch) for e in t if e]
output:
['1', 'A', '2', 'B', '3', 'C', '6']
first, you create 2 lists, one with the strings that represent numbers and a second list with the letters then you sort them and combine using list comprehension and itertools.zip_longest