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'

2 Answers 2

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'.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.