Custom sorting in Python

Asked

Viewed 92 times

0

I have a list foo = ["BCB", "CAB", "CBC"] and a specific alphabetical order bar = "ACB".

The result with that specific order should be resultado = ["CAB", "CBC", "BCB"]

How do I sort that list?

  • That? https://answall.com/q/259493/101

1 answer

1


Hello, you can use the following:

foo = ["BCB", "CAB", "CBC"]
bar = "ACB"
foo_new = sorted(foo, 
          key = lambda ordenar: [bar.index(i) if i in bar else ord(i) for i in ordenar])

Or this, which uses your desired order in dincionario:

bar2 = {'A': 0, 'C': 1, 'B': 2}
foo2 = ["BCB", "CAB", "CBC"]
foo_new2 = sorted(foo2, 
           key=lambda ordenar: [bar2.get(i, ord(i)) for i in ordenar])

Credits to this topic of Stackoverflow in English : https://stackoverflow.com/questions/27253274/python-sorting-according-to-a-different-alphabetic-order

Browser other questions tagged

You are not signed in. Login or sign up in order to post.