-2
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]]
  • 2
    Does this answer your question? [Sorting list based on values from another list](https://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list) – Michael Szczesny Feb 14 '22 at 12:39

3 Answers3

1

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]
0xDEADBEEF
  • 66
  • 7
0

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)

se her
  • 26
  • 3
-1

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)])
Ben Grossmann
  • 4,387
  • 1
  • 12
  • 16