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

后端 未结 7 618
心在旅途
心在旅途 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条回答
  •  -上瘾入骨i
    2021-01-02 05:26

    If you actually don't care about the efficiency at all, and just want in-place semantics (which is a bit odd, because there are entire programming languages dedicated to avoiding in-place semantics), then you can do this:

    def modifyList(toModify, newList):
        toModify[:] = newList
    
    def permuteAndUpdate(toPermute, permutation):
        modifyList(toPermute, [toPermute[i] for i in permutation])
    
    permuteAndUpdate(spam_list, spam_order)
    
    print(spam_list)
    # ['We', 'are', 'the', 'Ni', 'knights', 'who', 'say']
    

    Credit goes to senderle for recognizing that this is what the OP may actually be after; he should feel free to copy this answer into his own. Should not accept this answer unless you really prefer it over his.

提交回复
热议问题