If I have sublist A: [‘E’,’C’, ‘W’], what is the most pythonic way to order the sublist according to the order of master list M: [‘C’,’B’,’W’,’E’,’K’]
My solution is seems rather rudimentary. I am curious if there is a more ‘pythonic’ way to get the same result.
ORDER = ['C','B','W','E','K']
possibilities = ['E','C', 'W']
possibilities_in_order = []
for x in ORDER:
if x in possibilities: possibilities_in_order.append(x)
How this works: for each
elementinpossibilities,order.index(element)is called, and the list is simply sorted by those respective positions.More details: Built-in Functions →
sorted.