根据字符串列表对列表列表进行排序 [英] Sorting a list of lists based on a list of strings

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

问题描述

如果我有一个列表:

arr = ['b', 'd', 'a', 'c']

以及类似的列表列表:

stats = [['a', 35, 109], ['b', 100, 50], ['c', 30, 80], ['d', 40, 50]]

我想根据"arr"订购"stats".所以,我想要:

I would like to order "stats" according to "arr". So, I want:

stats = [['b', 100, 50], ['d', 40, 50], ['a', 35, 109], ['c', 30, 80]]

在Python中有一种简单的方法吗?

Is there an easy way to do that in Python?

谢谢

推荐答案

您可以将sorted与键函数一起使用,该函数根据arr中第一个元素的索引对嵌套列表进行排序:

You can use sorted with a key function which sort the nested list based on the index of first element in arr :

>>> arr = ['b', 'd', 'a', 'c']
>>> stats = [['a', 35, 109], ['b', 100, 50], ['c', 30, 80], ['d', 40, 50]]
>>> sorted(stats,key=lambda x:arr.index(x[0]))
[['b', 100, 50], ['d', 40, 50], ['a', 35, 109], ['c', 30, 80]]
>>> 

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

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