gpt4 book ai didi

python - a[len(a) :] = [x] and a[len(a)] = [x] 之间的区别

转载 作者:太空宇宙 更新时间:2023-11-03 12:46:35 28 4
gpt4 key购买 nike

为什么a[len(a):] = [x]等同于a.append(x),但是a[len(a) ] = [x] 给出超出范围的错误?

最佳答案

根据 the 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 - a[len(a) :] = [x] and a[len(a)] = [x] 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32973725/

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