简体   繁体   English

从排序列表中排序子列表的大多数pythonic方法

[英]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'] 如果我有子列表A:['E','C','W'],根据主列表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. 我很好奇是否还有一种更“ pythonic”的方式来获得相同的结果。

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. 它是如何工作的:对于possibilities每个elementorder.index(element)调用order.index(element) ,并且列表仅按这些位置进行排序。

More details: Built-in Functions → sorted . 更多详细信息: 内置函数→已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. 之所以为O(n),是因为它仅遍历主列表一次,并且如果子列表的大小与主列表接近,则效果会很好。

This also assumes that possibilities has no duplicates. 这也假设possibilities没有重复。 You can handle that if necessary, however, although it will make the code more complex. 尽管可以使代码更加复杂,但是您可以根据需要进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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