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