根据另一个列表对元组列表进行排序? [英] Sorting tuple list based on another list?

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

问题描述

有两个列表.

list1 = [('ST00003', '009830'), ('ST00003', '005490'), ('ST00003', '005830'), ('ST00003', '251270'), ('ST00002', '111710')]
list2 = ['111710', '005830', '009830', '005490', '251270']


我想按list2的顺序对list1进行排序.

I want to sort list1 in order of list2.

list3 = [('ST00002', '111710'), ('ST00003', '005830'), ('ST00003', '009830'), ('ST00003', '005490'), ('ST00003', '251270')]

我想让它在排序时像 list3 一样.有什么好办法吗?

I want to make it like list3 when it's sorted. Is there any good way?

推荐答案

我做了一个中间的 dict ,它从数字字段映射到 list2 中的索引:

I did it my making an intermediate dict which maps from the number field to the index in list2:

list1 = [('ST00003', '009830'), ('ST00003', '005490'), ('ST00003', '005830'), ('ST00003', '251270'), ('ST00002', '111710')]
list2 = ['111710', '005830', '009830', '005490', '251270']

map2 = {value:index for index,value in enumerate(list2)}
print(map2)

list3 = sorted(list1, key = lambda i: map2[i[1]])
print(list3)

根据需要输出.

这篇关于根据另一个列表对元组列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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