Home > front end >  How to make the 1st element of list of lists to match the order of elements in another list?
How to make the 1st element of list of lists to match the order of elements in another list?

Time:02-01

How can I make the 1st element of list of lists to match the order of elements in another list? For example:

list1 = [3, 7, 1, 10, 4]
list2 = [[1,0],[3,2],[4,11],[7,9],[10,1]]

newlist = [[3,2],[7,9],[1,0],[10,1],[4,11]]

CodePudding user response:

You can use list.index:

list1 = [3, 7, 1, 10, 4]
list2 = [[1, 0], [3, 2], [4, 11], [7, 9], [10, 1]]

newlist = sorted(list2, key=lambda l: list1.index(l[0]))
print(newlist)

Prints:

[[3, 2], [7, 9], [1, 0], [10, 1], [4, 11]]

If the lists are large, I'd suggest to create a mapping from list1 and use that in the sorting key function:

m = {v: i for i, v in enumerate(list1)}
newlist = sorted(list2, key=lambda l: m[l[0]])

print(newlist)

CodePudding user response:

If the firsts in the second list are always a permutation of the first list (i.e., if that's not a misleading example):

firsts = next(zip(*list2))
first2full = dict(zip(firsts, list2))
newlist = [*map(first2full.get, list1)]

Try it online!

  • Related