为什么扩展的切片分配比常规的切片分配不那么灵活? [英] Why is extended slice assignment less flexible than regular slice assignment?

查看:84
本文介绍了为什么扩展的切片分配比常规的切片分配不那么灵活?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据扩展切片上的Python文档:

According to the Python documentation on extended slices:

如果您具有可变的序列(例如列表或数组),则可以 分配或删除扩展片,但有一些区别 在分配给扩展片和常规片之间.分配给 常规切片可用于更改序列的长度:

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:

>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]

扩展切片并不灵活.分配给扩展时 切片,语句右侧的列表必须包含 与要替换的切片数量相同的项目:

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:

>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2

我不明白为什么普通"切片方法有效,但扩展"切片方法无效.是什么将普通"切片与扩展"切片区分开来?为什么扩展"切片方法失败?

I do not understand why the "ordinary" slice method works but the "extended" slice method doesn't work. What differentiates an "ordinary" slice from an "extended" slice, and why does the "extended" slice method fail?

推荐答案

如果您想像如何,则更容易发现问题

It's a little easier to see the problem if you try to imagine how

a[::3] = [0, 1, 2]

可以使用4个项目的列表:

would work with a 4-item list:

+---+---+---+---+   +   +---+
| a | b | c | d |       | ? |
+---+---+---+---+   +   +---+
  ^           ^           ^
+---+       +---+       +---+
| 0 |       | 1 |       | 2 |
+---+       +---+       +---+

我们正试图替换第三个值,但我们的列表不够长,因此,如果我们继续前进,最终将得到某种奇怪的科学怪人列表,其中某些项实际上并不存在.如果有人随后尝试访问a[5]并获得了IndexError(即使a[6]正常工作),他们会感到非常困惑.

We're trying to replace every third value, but our list isn't long enough, so if we went ahead anyway we'd end up with some kind of weird frankenstein list where some of the items don't actually exist. If someone then tried to access a[5] and got an IndexError (even though a[6] works normally), they'd get really confused.

尽管从技术上讲,您可以通过将a扩展一个来避开a[::2]情况,但是为了保持一致性,Python禁止所有扩展的切片分配,除非已经有一个取值的地方.

Although you could technically get away with the a[::2] case by extending a by one, for the sake of consistency, Python bans all extended slicing assignments unless there's already a place for the value to go.

常规切片的步幅始终为1,因此不会出现任何间隙,因此可以放心地进行分配.

A regular slice always has a stride of one, so there's no chance of any gaps occurring, and so the assignment can safely be allowed.

这篇关于为什么扩展的切片分配比常规的切片分配不那么灵活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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