python - 具有相等边界的切片分配

标签 python slice

如果边界相等,则切片间隔为空,因此分配给它应该分配给任何内容,并且列表应该保持不变,对吗?

>>> l = [0, 1, 2, 3]
>>> l[1:1]
[]   # (as expected)
>>> l[1:1] = [4]
>>> l
[0, 4, 1, 2, 3]
# why did 4 get in there?

最佳答案

assign to nothing, and the list should remain unmodified

不,它不会用该值替换任何内容。之前,l[1]l[1] 之间没有任何内容,现在是 E。您也可以尝试

l = ['a', 'b', 'c', 'd']
l[1:3]='E'

这将导致 l['a', 'E', 'd'],而不是 ['a', 'E', 'E', 'd']:您命名的切片将被值替换。如果你这样做

l = ['a', 'b', 'c', 'd']
l[1:2]=['E','F','G']

这将导致 l['a', 'E', 'F', 'G', 'c', 'd']

关于python - 具有相等边界的切片分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57210892/

相关文章:

python - itertools 和跨步列表赋值

xcode - xcode Assets 切片中线的含义?

go - 使用带有标量或 slice 的函数

java - Google Cloud Function可自动创建Windows vm密码

python - 我如何在数据帧python中找到非时间戳数据?

python - 如何替换 PYTHON 列表中每一行的第一个元素?

struct - Golang - 嵌套结构中的 slice

python - 通过在 Python 中切片列表来分配值的紧凑方法

python - 将变量添加到 Keras/TensorFlow CNN 密集层

python - 类和实例的相同方法