gpt4 book ai didi

python - 为什么我不能将任意可迭代对象分配给步长为 -1 的扩展切片?

转载 作者:太空狗 更新时间:2023-10-30 00:11:46 25 4
gpt4 key购买 nike

Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> u = [4, 5, 6, 7, 8, 9]
>>> u[1::1] = [3, 2, 1, 0]
>>> u
[4, 3, 2, 1, 0]
>>> u[9:0:-1] = [8, 7, 6, 5]
>>> u
[4, 5, 6, 7, 8]
>>> u[9:0:-1] = [16, 12, 8]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 3 to extended slice of size 4
>>> u
[4, 5, 6, 7, 8]
>>>

预期行为:最终赋值语句没有抛出异常; u 应在最后一行打印为 [4, 8, 12, 16]

我可以分配给步长为 1 的扩展切片,即使我分配的 iterable 是“错误的长度”。为什么我不能分配给步长为 -1 的扩展切片并使其以明显的方式工作?

最佳答案

我认为创建一个步长为 1 的扩展切片实际上就像一个普通切片而不是一个扩展切片。

扩展切片不允许您更改序列的长度,如前所述here

If you have a mutable sequence such as a list or an array you can assign to or delete an extended slice, but there are some differences between assignment to extended and regular slices. Assignment to a regular slice can be used to change the length of the sequence. Extended slices aren't this flexible. When assigning to an extended slice, the list on the right hand side of the statement must contain the same number of items as the slice it is replacing.

至于为什么会这样,我只能猜测是因为在没有明显行为的情况下。举个例子:

u = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
u[0:8:3] = [ 10, 11 ]

您希望它如何运作?我想你可以用 10 和 11 替换 1 和 4,但是 7 呢?你离开它吗?删除它?删除 7 之后的整个剩余序列?也许这只是我,但这个案子似乎不太明确。我想这就是为什么扩展切片不允许这种行为的原因。

关于python - 为什么我不能将任意可迭代对象分配给步长为 -1 的扩展切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10963595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com