简体   繁体   English

无法在python中交换列表中的多个元素

[英]Unable to swap multiple elements in a list in python

I'm new to python and am trying to make a function that swaps multiple values in a list at once.我是 python 的新手,正在尝试创建一个函数来一次交换列表中的多个值。

def swap(deck: List[int], start1: int, end1: int, start2: int, end2: int) -> None: 

    start1 = start1 % len(deck)
    start2 = start2 % len(deck)


    end1 = end1 % len(deck)
    end2 = end2 % len(deck)

    if start1 < start2:
        deck[start1: end1], deck[start2: end2] = deck[start2: end2], deck[start1: end1]
    else:
        deck[start2: end2], deck[start1: end1] = deck[start1: end1], deck[start2: end2]

when deck = [0,1,2,3,4,5,6,7,8,9,10] swap(deck, -3, 11, 0, 2) should mutate the deck to be [8,9,2,3,4,5,6,7,0,1,10] , but I get this instead [2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 10]deck = [0,1,2,3,4,5,6,7,8,9,10] swap(deck, -3, 11, 0, 2)应该将deck变为[8,9,2,3,4,5,6,7,0,1,10] ,但我得到这个[2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 10]

I have also tried it with the temp variable method我也用临时变量方法试过了

    temp = deck[start1: start1]

    deck[start1: start1] = deck[start2: end2]

    deck[start2: end2] = temp

but I get the same result... An explanation of why this is happening and how I can fix it is greatly appreciated.但我得到了相同的结果......非常感谢解释为什么会发生这种情况以及我如何解决它。

Because your two ranges are not the same size, the deck list changes size after the first assignment, so the range where the temp content is assigned does not correspond to the original positions.因为你的两个范围大小不一样,所以第一次分配后deck list改变了大小,所以临时内容分配的范围和原来的位置不对应。

for example:例如:

deck = [0,1,2,3,4,5,6,7,8,9,10]
temp = deck[0:2]         # temp is [0,1]  
deck[0:2] = deck[-3:11]  # deck is now [8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10]
deck[-3:11] = temp       # [8,9] is replaced by [0,1] 
                         # because -3 is now at position 9 instead of  8

one way to fix this (assuming your ranges never overlap) is to form a concatenation of the 5 slices of the deck: [before range1]+[range2]+[between ranges]+[range1]+[after range2], or more specifically, assign the total subrange with the concatenation of the 3 middle parts解决这个问题的一种方法(假设你的范围从不重叠)是形成甲板的 5 个切片的串联:[范围 1 之前]+[范围 2]+[范围之间]+[范围 1]+[范围 2 之后],或更多具体来说,用 3 个中间部分的串联分配总子范围

deck[start1:end2] = deck[start2:end2] + deck[end1:start2] + deck[start1:end1]

Basically, what you want to do is:基本上,你想要做的是:

deck = deck[s2:e2] + deck[e1:s2] + deck[s1:e1]

Don't try to use two variables before and after the equal sign = .不要尝试在等号=前后使用两个变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM