marc
marc

Reputation: 2197

How to order list according to array values in python?

Lets say I have:

list = ['apple','banana','pear','orange']
values = [3,1,2,4]

I need to order the list strings according to their values in the "values" vector. In MatLab I would have merged the two then sort the vector, but it doesn't seem like I can do that here. Any ideas?

Thanks!

Upvotes: 2

Views: 116

Answers (4)

jabaldonedo
jabaldonedo

Reputation: 26582

This could work for you. Use zip to pair both lists and then sort, finally get the new list.

>>> mylist = ['apple','banana','pear','orange'] 
>>> values = [3,1,2,4]
>>> [i[1] for i in sorted(zip(values, mylist))]
 ['banana', 'pear', 'apple', 'orange']

By the way don't use list for naming your list.

You can also use itertools.izip which is like zip() except that it returns an iterator instead of a list, and therefore you can get better performance

>>> from itertools import izip
>>> mylist = ['apple','banana','pear','orange'] 
>>> values = [3,1,2,4]
>>> [i[1] for i in sorted(izip(values, mylist))]
 ['banana', 'pear', 'apple', 'orange']

Upvotes: 9

MONTYHS
MONTYHS

Reputation: 924

Better to use Dict object, if key value pair present use the dict it easy to process....

Upvotes: 0

zaplec
zaplec

Reputation: 1819

Try using numpy argsort. Change the list and values to numpy array

list = np.asarray( list )
values = np.asarray( values )

idxs = np.argsort(values)
list = list[:,idxs]

Just got it in my mind. Haven't tested this, but I think that should do it.

Upvotes: 0

Erik Kaplun
Erik Kaplun

Reputation: 38247

This should do it:

[i[1] for i in sorted(enumerate(list), key=lambda (ix, _): values[ix])]

gives

['banana', 'pear', 'apple', 'orange']

EDIT: jabaldonedo's answer is definitely the best one.

Upvotes: -1

Related Questions