根据另一个列表的顺序重新排列列表 [英] Rearranging list based on order of another list

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

问题描述

我确定以前可能已经问过这个问题,但是我似乎找不到正确的答案.如果我有两个列表

I am sure this question has possibly been asked before but I can't seem to find the correct answer. If I have two lists

_list1 = ["keyName", "test1", "test2"]
_list2 = ["keyName", "test2", "test1"]

我正在尝试使用_list1重新排列_list2中的元素,以便它们与顺序完全匹配.什么是最干净的方法?所需的输出:

I am trying to use _list1 to rearrange elements in _list2 so that they match the order exactly. What's the cleanest way to do that? Desired output:

_list1 = ["keyName", "test1", "test2"]
_list2 = ["keyName", "test1", "test2"]

很抱歉,如果这是重复的,但到目前为止,我只能使用压缩的sorted()方法找到数字列表的答案.

I am sorry if this is duplicate but so far I am only able to find answers for list of numbers and using zipped sorted() method.

如果_list2是列表列表怎么办?

What if the _list2 is a list of lists?

_list2 = [["test1", "test2", "keyName"], ["test2", "test1", "keyName"]]

所需的输出:

_list2 = [["keyName", "test1", "test2"], ["keyName", "test1", "test2"]]

如果发生以下情况,该怎么办:如果我想使用_list1作为键来对其他任何对象列表进行排序,该怎么办

One more what if: What if I wanted to sort any other list of objects using _list1 as a key

_list2 = [[object1, object2, object3], [object1, object2, object3]]

其中:

object1.Name = "keyName"
object3.Name = "test1"
object2.Name = "test2"

我希望如此有效地输出:

so effectively I would expect output of:

_list2 = [[object1, object3, objec1], [object1, object3, objec1]]

有可能吗?

推荐答案

In [84]: _list1 = ["keyName", "test1", "test2"]

In [85]: d = {k:v for v,k in enumerate(_list1)}

In [86]: _list2 = ["keyName", "test2", "test1"]

In [87]: _list2.sort(key=d.get)

In [88]: _list2
Out[88]: ['keyName', 'test1', 'test2']

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

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