0

I want to order myList based on the another list(myorderList) which stores the order of it. For example, myorderList=[3,1,2] indicates that the first element of myList is mapped to "two" because the smallest number is 1 in myorderList and then "one" and final element mapped to "zero" according to order of myorderList.

I have done this it works but i feel that it is not a good method to map the order of myList. I am looking for a better way to do that.

    myorderList=[]
    myneworderedList=[]
    myList=["zero","two","one"]
    myorderList=[3,1,2]
    for i in range(len(myList)):# just to eliminate index out of range error
        myneworderedList.append(i)

    for index,item in enumerate(myorderList):
        myneworderedList[int(item)-1]=myList[index]
    print myneworderedList

The result:

['two', 'one', 'zero']
Co Koder
  • 2,021
  • 7
  • 31
  • 39

1 Answers1

4

One option is to zip the two lists together, sort, and extract only the bits you are interetsed in from the result:

>>> [y for x, y in sorted(zip(myorderList, myList))]
['two', 'one', 'zero']

Another option is to use a custom key function that returns the order keys in the correct order:

>>> it = iter(myorderList)
>>> sorted(myList, key=lambda x: next(it))
['two', 'one', 'zero']

Python gurantees that the key function is called once per item of the input list and in the right order.

More specifically, before starting to sort the input list, the sorted() implementation iterates over the list and calls the key function for each item. The key function given above ignores its argument and simply returns the next item from myorderList, which results in the desired key being used for each element of myList. After this, sorted() sorts the list according to the previously determined keys.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841