如何根据另一个列表对列表进行排序? [英] How to sort a list according to another list?
问题描述
有一个列表:
a = [("ax", 1), ("ec", 3), ("bk", 5)]
另一个列表:
b = ["ec", "ax", "bk"]
我想根据b
对a
进行排序:
sort_it(a, b)
a = [("ec", 3), ("ax", 1), ("bk", 5)]
该怎么做?
推荐答案
a.sort(key=lambda x: b.index(x[0]))
此操作使用a
中每个元组的第一个元素的b
中的索引作为其排序依据的值对a
进行就地排序.
This sorts a
in-place using the the index in b
of the first element of each tuple from a
as the values it sorts on.
另一种可能更简洁的书写方式是:
Another, possibly cleaner, way of writing it would be:
a.sort(key=lambda (x,y): b.index(x))
如果您有大量项目,则做一些不同的事情可能会更有效率,因为.index()
在很长的列表上可能是一项昂贵的操作,并且您实际上不需要进行完整的排序,因为您已经知道订单了:
If you had large numbers of items, it might be more efficient to do things a bit differently, because .index()
can be an expensive operation on a long list, and you don't actually need to do a full sorting since you already know the order:
mapping = dict(a)
a[:] = [(x,mapping[x]) for x in b]
请注意,这仅适用于2元组的列表.如果您希望它适用于任意长度的元组,则需要对其进行一些修改:
Note that this will only work for a list of 2-tuples. If you want it to work for arbitrary-length tuples, you'd need to modify it slightly:
mapping = dict((x[0], x[1:]) for x in a)
a[:] = [(x,) + mapping[x] for x in b]
这篇关于如何根据另一个列表对列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!