a[len(a):]=[x]和a[len(a)]=[x]之间的差异

2024-04-27 00:12:31 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么a[len(a):] = [x]等同于a.append(x),而{}给出了一个超出范围的错误?在


Tags: len错误append超出范围
3条回答

因为这是语言做出的明确选择;分配给索引需要这些索引存在。分配给切片将根据需要展开或缩小列表以适应新的大小。在

Perthe documentation(重点是我的):

  • If the target is a subscription: ...

    If the primary is a mutable sequence object (such as a list), the subscript must yield a plain integer. If it is negative, the sequence’s length is added to it. The resulting value must be a nonnegative integer less than the sequence’s length, and the sequence is asked to assign the assigned object to its item with that index. If the index is out of range, IndexError is raised (assignment to a subscripted sequence cannot add new items to a list)

    ...

  • If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to (small) integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. 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 object allows it.

因此,对切片的赋值可以更改列表的长度,但对索引(订阅)的赋值则不能。在

Python的切片通常比用数字索引(按设计)更“宽容”。例如:

lst = []
lst[1:100]  # No exception here.

我认为切片分配只是这种“宽容”的延伸。有趣的是,你甚至可以使用超出范围的指数:

^{pr2}$

相关问题 更多 >