1

I have an array like this:

master = ['aa','bb','cc','dd','ee','ff']

I need to sort it according to this:

order = ['c','e','a','b']

So the final answer would look like:

['cc','ee','aa','bb','dd','ff']

The problem is that if the item is not in the order array then it would go to the end, and I'm not sure how to do that.

How would you approach this? I tried:

master.sort(key=lambda x: order.index(x))

But it will crash if x is not in the order array, for example 'dd' and 'ff'

Fri Gate
  • 21
  • 1
  • 4

2 Answers2

1

You could use maketrans and translate:

master = ['aa','bb','cc','dd','ee','ff']
order = 'ceab'
trantab = str.maketrans(order, 'abcdefghijklmnopqrstuvwxyz'[:len(order)])
master.sort(key=lambda x: x.translate(trantab))

Depending on your expectations with order values like 'fecd', you could also create the translation table as follows:

trantab = str.maketrans(order, ''.join(sorted(order)))

...which would keep 'a' and 'b' sorted before 'f'.

trincot
  • 317,000
  • 35
  • 244
  • 286
0
master = ['aa','bb','cc','dd','ee','ff']
order = 'ceab'

sorted(master, key = lambda word: [order.index(c) if c in order else ord(c) for c in word])

See Python: Sorting according to a different alphabetic order for more details.

Community
  • 1
  • 1
blacksite
  • 12,086
  • 10
  • 64
  • 109