Reordering a list by ordering another list in python

I'm sure this question may have 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"]

      

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

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

      

I apologize if this is a duplicate, but for now I can only find answers for a list of numbers and use the zipped sorted () method. Thank you!

What if _list2 is a list of lists?

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

      

Desired output:

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

      

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

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

      

Where:

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

      

so efficiently I would expect the output:

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

      

possibly?

+3


source to share


2 answers


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']

      



+3


source


try using a sorted key:

sorted(_list2,key=_list1.index)

      



for nested list you can use list comphresnion:

[sorted(x,key=_lis1.index) for x in _list2]

      

+6


source







All Articles