0

I have two separate lists one list contain list of lists(list1) and another list is simple numeric values. The list2 is sorted but i want to sort list1 based on the values of list2 .Using Zip method it is gives errors:unhashable type.

list1=[[1 ,2],[2,1],[1,3],[1,9],[6,9],[3,5],[6,8],[4,5],[7,9]]
list2=[0.0,1.4142135623730951,1.0,7.0,8.602325267042627, 3.605551275463989,7.810249675906654,4.242640687119285,9.219544457292887]
keydict=dict(zip(list1,list2))//Gives errror: unhashable type

.Can Anybody suggest solution.

  • _The list2 is sorted_ : **no** - it is not `0.0 <1.4142135623730951 > 1.0 ...` - unclear. There is a plethora of questions on SO of sorting lists based on other lists, based on objects-attributes in other lists etc. This is a dupe - did none other post help you out? – Patrick Artner Apr 04 '19 at 06:39

2 Answers2

3

You can use zip() + sorted():

[x for x, _ in sorted(zip(list1, list2), key=lambda x: x[1])]

Code:

list1 = [[1 ,2],[2,1],[1,3],[1,9],[6,9],[3,5],[6,8],[4,5],[7,9]]
list2 = [0.0,1.4142135623730951,1.0,7.0,8.602325267042627, 3.605551275463989,7.810249675906654,4.242640687119285,9.219544457292887]

print([x for x, _ in sorted(zip(list1, list2), key=lambda x: x[1])])
# [[1, 2], [1, 3], [2, 1], [3, 5], [4, 5], [1, 9], [6, 8], [6, 9], [7, 9]]
Austin
  • 25,759
  • 4
  • 25
  • 48
0

Use the below list comprehension:

print([list1[list2.index(i)] for i in sorted(list2)])

Output:

[[1, 2], [1, 3], [2, 1], [3, 5], [4, 5], [1, 9], [6, 8], [6, 9], [7, 9]]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114