简体   繁体   中英

most pythonic way to order a sublist from a ordered list

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)
>>> order = ['C','B','W','E','K']
>>> possibilities = ['E','C','W']
>>> possibilities_in_order = sorted(possibilities, key=order.index)
>>> possibilities_in_order
['C', 'W', 'E']

How this works: for each element in possibilities , order.index(element) is called, and the list is simply sorted by those respective positions.

More details: Built-in Functions → sorted .

possibilities.sort(key=lambda x : ORDER.index(x))

Here's a linear-time solution:

posset = set(possibilities)
[letter for letter in order if letter in posset]

This filters the master list for only the members of the sublist. It's O(n) because it only traverses the master list once, and will perform well if the sublist is close in size to the master list.

This also assumes that possibilities has no duplicates. You can handle that if necessary, however, although it will make the code more complex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM