0

I have the list of strings:

['bsdf', 'dfgds', 'asdf']

I defined alphabet order:

'dfgsab'

I would like to sort my strings according to the order defined in my alphabet. So in this example the output would be:

['dfgds', 'asdf', 'bsdf']

How should I do it in the most efficient way?

pw94
  • 391
  • 2
  • 5
  • 21

1 Answers1

7

Use a combination of sorted, the key= argument and str.index:

strings = ['bsdf', 'dfgds', 'asdf']
order = 'dfgsab'
sorted(strings, key=lambda s: [order.index(c) for c in s])

output

['dfgds', 'asdf', 'bsdf']
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47