-4

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!

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 3
    Did you tried anything? – Gokul nath Mar 17 '20 at 16:03
  • Hello and welcome to StackOverflow! You seem to be under the impression that StackOverflow is a site where you post a problem and get some code in return. This is in fact not the case. Your question will most likely be closed or even deleted shortly. To prevent this from happening in the future, please [take the tour](https://stackoverflow.com/tour) and [take a look at the help center](https://stackoverflow.com/help). In particular, [make yourself famlilar as to what is regarded as on-topic around here](https://stackoverflow.com/help/on-topic) – azro Mar 17 '20 at 16:04
  • 4
    It isn't clear to me what the logic behind this sorting order is. There are multiple ways to interpret it that would result in this order. – interjay Mar 17 '20 at 16:05
  • check this question: https://stackoverflow.com/questions/7946798/interleave-multiple-lists-of-the-same-length-in-python – Ala Tarighati Mar 17 '20 at 16:08

2 Answers2

2

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.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
1
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

kederrac
  • 16,819
  • 6
  • 32
  • 55