用打包的元组替换列表切片

Replace a list slice with a packed tuple

我有一个元组形式的点列表:

myList = [(1,1), (2,2), (3,3), (4,4), (5,5)]

我想用一个新的元组替换可变长度的切片 (6,6) 所以结果是这样的:

myList = [(1,1), (6,6), (5,5)]

我尝试将元组分配给切片,但这解压了元组。

startIndex = 1
endIndex = 3
newTuple = (6,6)
myList[startIndex:endIndex] = newTuple
#myList == [(1, 1), 6, 6, (4, 4), (5, 5)]

下面是我当前的方法,但我想知道是否有解决此自动解包的方法,以及是否有更好或更易读的方法来执行此操作。

myList[startIndex] = newTuple
del myList[startIndex+1:endIndex]

您需要将元组(一个值)包装在一个列表中:

myList[startIndex:endIndex] = [newTuple]

切片赋值总是遍历右侧对象;您正在用另一个索引列表替换一个索引列表。

来自赋值语句文档:

Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the object allows it.

由于您提供了一个简单的元组,元组中的元素用于替换切片索引。通过将它包装在列表中,您的元组是该列表中的一个元素,并且本身不会进一步解压缩:

>>> myList = [(1,1), (2,2), (3,3), (4,4), (5,5)]
>>> startIndex = 1
>>> endIndex = 3
>>> newTuple = (6,6)
>>> myList[startIndex:endIndex] = [newTuple]
>>> myList
[(1, 1), (6, 6), (4, 4), (5, 5)]
>>> myList = [(1,1), (2,2), (3,3), (4,4), (5,5)]
>>> myList[1:4] = [(6,6)]
>>> myList
[(1, 1), (6, 6), (5, 5)]