如何根据另一个列表对元组列表进行排序 [英] How to sort a list of tuples according to another list

查看:32
本文介绍了如何根据另一个列表对元组列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个列表:

a = [("ax", 1), ("ec", 3), ("bk", 5)]

另一个列表:

b = ["ec", "ax", "bk"]

我想根据ba进行排序:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆