这在 [任何以前的版本] 之前的 Python 中是否可行

Was this possible in Python before [any previous version]

我依稀记得这东西很久以前就可以用了 有谁知道这段代码以前是否真的有效? 如果自更新的 python 版本以来已弃用此功能?

代码

# My python version is 3.8

lst = ['a', 'b', 'c', 'd']
lst[0:3] = 100
print(lst)

当前输出

TypeError: can only assign an iterable

预期输出

[100, 'd']

谢谢

这在任何版本中都不起作用,因为切片赋值需要一个类似序列的对象来赋值。

它不起作用的原因是您需要将其转换为单项序列,如下所示:

lst = ['a', 'b', 'c', 'd']
lst[:3] = [100]
print(lst)

或者用一个元组:

lst = ['a', 'b', 'c', 'd']
lst[:3] = 100,
print(lst)

由于lst[:3]给出了一个序列对象,所以你分配给它的对象也需要是一个序列对象。

这在 python 的任何版本中都是不可能的...因为不使用单个项目序列进行索引是唯一的方法。像这样:

lst = ['a', 'b', 'c', 'd']
lst[3] = 100
print(lst)

但是所有 python 版本都需要切片序列。

documentation for python 3, documentation of python 2所述:

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 target sequence allows it.

正如我在 Python 1.4 的文档中看到的:

If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (e.g. a list). The assigned object should be a sequence object of the same type.

此文档于 1996 年发布。

所以 25 年来,这不可能,python docs 是 1996 年,但实际上 python 1 是 1994 年开始的。

所有版本文档引用都是相同的。

对于 Python 自己的内置类型,这在以前是不可能的,至少在过去 20 年多的时间里是这样。

Assignment Statements

If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (e.g. a list). The assigned object should be a sequence object of the same type. […]

-- Python 1.4, documentation released on 25 October 1996.

相同的语句出现在 all published documentation 直到当前版本。


请注意,根据数据模型,语义 Python 没有这样的限制。

Data Model: Emulating sequence and mapping types

__setslice__(self, i, j, sequence) Called to implement assignment to self[i:j]. The sequence argument can have any type. The return value should be None. Same notes for i and j as for __getslice__.

-- Python 1.4, documentation released on 25 October 1996.

自定义类型,最突出的是 numpy.array,可以随意解释标量的切片赋值。