3
votes

Input

a= (92, 93, 94, 95)
b= [0.76, 0.46, 0.56,0.64]

required is the sorting of list a based on list b in descending order

a= [92, 95, 94, 93]
b= [0.76, 0.64, 0.56, 0.46]

I used

a,b = zip(*sorted(zip(a,b), key=operator.itemgetter(0), reverse=True))

I tried to use it to sort in ascending order and then try to use another list to write in the reverse order.

The error is :

key=operator.itemgetter(0), reverse=True))
NameError: name 'operator' is not defined

any suggestions?

2

2 Answers

4
votes

The error that you see is because you need to import the operator module. Even doing that does not fix the problem though.

Instead you can do it like this:

b, a = zip(*sorted(zip(b,a), reverse=True))

For your data:

>>> a = [92, 93, 94, 95]
>>> b = [0.76, 0.46, 0.56,0.64]
>>> b, a = zip(*sorted(zip(b,a), reverse=True))
>>> a
(92, 95, 94, 93)
>>> b
(0.76, 0.64, 0.56, 0.46)

This gives you tuples. If you really want/need lists:

>>> a = [92, 93, 94, 95]
>>> b = [0.76, 0.46, 0.56,0.64]
>>> b, a = (list(x) for x in zip(*sorted(zip(b,a), reverse=True)))
>>> a
[92, 95, 94, 93]
>>> b
[0.76, 0.64, 0.56, 0.46]
0
votes

Did you import operator?

Not that it is needed:

z = list(zip(a, b))
z = sorted(z, key=lambda i: i[1], reverse=True)
a, b = list(zip(*z))