Sjn73
Sjn73

Reputation: 189

How to rearrange nested list based on particular index

I am having a nested list as below:

nli=[[123,12],[124,15],[127,19],[12,6]]

I want to rearrange the above nested list based on the another list li:

li=[15,6,12,19]

Where li values corresponds to the second element of the nested list nliSo how can I rearrange the nli based on the order of the li which intern corresponds to the second element of the each nested list nli Output after rearranging nli suppose be:

[[124, 15], [12, 6], [123, 12], [127, 19]]

Also want to know where can I learn more about these kind of operations Thanks in advance!!

Upvotes: 3

Views: 1291

Answers (4)

Transhuman
Transhuman

Reputation: 3547

[j for i in li for j in nli if j[1]==i]
#Output
#[[124, 15], [12, 6], [123, 12], [127, 19]]

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

You can first create a dict that maps an element's value to the order in which it appeared in your list li.

>>> order = {k: i for i, k in enumerate(li)}
>>> order
{19: 3, 12: 2, 6: 1, 15: 0}

Then use that order to sort the original list based on each [1] element.

>>> sorted(nli, key = lambda i: order[i[1]])
[[124, 15], [12, 6], [123, 12], [127, 19]]

Upvotes: 2

Reut Sharabani
Reut Sharabani

Reputation: 31339

Map (create an index) by wanted key first:

by_second_item = {item[1]: item for item in nli}

Now use the mapping to create the new list:

rearranged = [by_second_item[i] for i in li]
# or: list(map(by_second_item.get, li))

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

You can sorted by using the index value of the last element in each value of nli:

nli=[[123,12],[124,15],[127,19],[12,6]]
li=[15,6,12,19]
new_list = sorted(nli, key=lambda x:li.index(x[-1]))

Output:

[[124, 15], [12, 6], [123, 12], [127, 19]]

Upvotes: 1

Related Questions