Custom ordering in Python

0

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

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

How do I sort this list?

    
asked by anonymous 17.02.2018 / 18:15

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 a dynamic:

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 for this Stackoverflow topic in English: link

    
18.02.2018 / 00:25