Home > OS >  sorting nested list based on another lis
sorting nested list based on another lis

Time:02-14

a = [[1,3,45,6,78,9],[2,6,5,88,3,4],[44,66,2,4,77,12]]
b = [4,6,3]

      

These are two lists in python, now each element in the first list a corresponds to the element in the list b with the same index. i.e a[0]:4,a[1]:6,a[2]:3 and so on.
Now I want to sort list b and then print the respective values corresponding to list a. I cannot use a dictionary because it gives an error that a is not hashable.
My desired output is:

x = [[44,66,2,4,77,12], [1,3,45,6,78,9], [2,6,5,88,3,4]]

CodePudding user response:

You can do :

a = [[1,3,45,6,78,9],[2,6,5,88,3,4],[44,66,2,4,77,12]]
b = [4,6,3]

c = sorted([[b[i],a[i]] for i in range(len(a))])
x = [i[1] for i in c]

CodePudding user response:

It can be done on a single line like:

a = [[1,3,45,6,78,9],[2,6,5,88,3,4],[44,66,2,4,77,12]]
b = [4,6,3]

c = [el for _, el in sorted(zip(b, a))]
print(c)

Output:

[[44, 66, 2, 4, 77, 12], [1, 3, 45, 6, 78, 9], [2, 6, 5, 88, 3, 4]]

(If the values in b are not unique, it will sort by first element in the corresponding the values from a)

CodePudding user response:

There is no issue using a dictionary as long as you avoid using any list as a key. In this case, you could use b for keys and a for values. For example,

d = dict(zip(b,a))
print([d[k] for k in sorted(d)])
  • Related