In-place way to apply a permutation to a list? (inverse of sorting-by-key)

后端 未结 7 613
心在旅途
心在旅途 2021-01-02 05:06

Here\'s a example of what I want to do

spam_list = [\"We\", \"are\", \"the\", \"knights\", \"who\", \"say\", \"Ni\"]
spam_order = [0,1,2,4,5,6,3]
spam_list.m         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-02 05:27

    You can give a special key to the sort function:

    order = dict(zip(spam_list, spam_order))
    spam_list.sort(key=order.get)
    

    Edit: As @ninjagecko points out in his answer, this is not really efficient, as it copies both lists to create the dictionary for the lookup. However, with the modified example given by the OP, this is the only way, because one has to build some index. The upside is that, at least for the strings, the values will not be copied, so the overhead is just that of the dictionary itself.

提交回复
热议问题