为什么不能为步长为-1的扩展片分配任意可迭代项? [英] Why can't I assign an arbitrary iterable to an extended slice whose step is -1?

查看:123
本文介绍了为什么不能为步长为-1的扩展片分配任意可迭代项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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]打印.

Expected behaviour: no exception thrown on final assignment statement; u should print on final line as [4, 8, 12, 16].

即使我要分配的可迭代长度是错误的长度",我也可以将其分配给步长为1的扩展切片.为什么然后我不能将其分配给步骤为-1的扩展片,并使其以明显的方式起作用?

I can assign to an extended slice whose step is 1, even if the iterable I'm assigning is "the wrong length". Why then can't I assign to an extended slice whose step is -1 and have it work in the obvious way?

推荐答案

我认为创建步长为1的扩展片实际上就像是常规片,而不是扩展片.

I think that creating an extended slice whose step is 1 effectively acts like a regular slice rather than an extended slice.

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

Extended slices do not allow you to change the length of the sequence, as noted 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.

至于为什么它如此工作,我只能猜测是由于没有明显行为的情况.举个例子:

As for why it's works this way, I can only guess it is because of the cases where there is no obvious behaviour. Take this example:

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

您希望它如何工作?我想您可以替换1& 4与10& 11,但是7呢?你离开吗?删除它?删除序列中剩余的7点之后的所有内容吗?也许只有我一个人,但这种情况似乎不太明确.我想假设的是为什么扩展切片不允许这种行为.

How would you expect this to work? I guess you could just replace 1 & 4 with 10 & 11, but what about 7? Do you leave it? Delete it? Delete the entire rest of the sequence past 7? Maybe it's just me, but this case doesn't seem too clear cut. Which I would assume is why this sort of behaviour just wasn't allowed for extended slices.

这篇关于为什么不能为步长为-1的扩展片分配任意可迭代项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆