python - Pythonic way: Sort array items based on a class member and another array -


i have tried imagine, can't seem arrive @ valid solution.

i need sort array of class objects based on id id same in list.

class item:   def __init__(self,i):     self.i =  itemlist = [item(2),item(1),item(4),item(3)] indexlist = [3,1,2,4] 

expected output:

itemlist_sorted = [item(3), item(1), item(2), item(4)] 

i have seen similar downvoted question here, solution did not me, since cannot use function , need compare member of each item index in array.

itemlist.sort(key=lambda x: x.i - indexlist.index) # wrong itemlist.sort(key=indexlist.index,cmp=lambda x,y: x.i==y) # wrong 

is there pythonic way accomplish without resorting c-like loop?

thanks in advance help!

the other answers address how sort correctly—but feel you're taking wrong approach here. why not build new list instead of trying sort old one?

[next(y y in itemlist if y.i == x) x in indexlist] 

note should faster using sort, has search indexlist once each of o(n log n) comparisons.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -