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?
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?
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