切片操作在python中实际返回什么

2024-04-27 04:55:32 发布

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

“所有切片操作都返回一个包含请求元素的新列表” 这来自python教程。你知道吗

但如果是这样的话,那么为什么这段代码会这样:

>>> a = [11, 3, 1999]
>>> a[:] = [9, 78]
>>> a
    [9, 78]

1)如果切片返回一个新列表,那么为什么我对新列表所做的绑定会影响原始列表。这说明了什么?你知道吗

但我也注意到:

>>> b = [4, 5, 6]
>>> b[:].append(5)
>>> b
[4, 5, 6]
>>> print(b)
[4, 5, 6]

2)这表明确实返回了一个新列表。当我们切一张单子时,到底发生了什么?你知道吗

请指出我的无知。提前谢谢。你知道吗


Tags: 代码元素列表切片教程单子printappend
1条回答
网友
1楼 · 发布于 2024-04-27 04:55:32

你把表达式赋值搞混了。获取值(读取)与设置值(写入)的处理方式不同。你知道吗

赋值(设置)重新使用语法来指定目标。在a[:] = ...这样的赋值中,a[:]是进行赋值的目标。在表达式中使用a[:]会生成一个新列表。你知道吗

换句话说:您有两个不同的语言语句,它们故意使用相同的语法。然而,它们仍然是不同的。你知道吗

参见Assignment statements reference documentation

assignment_stmt ::=  (target_list "=")+ (starred_expression | yield_expression)
target_list     ::=  target ("," target)* [","]
target          ::=  identifier
                     | "(" [target_list] ")"
                     | "[" [target_list] "]"
                     | attributeref
                     | subscription
                     | slicing
                     | "*" target

[...]

  • 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 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 target sequence allows it.

(我的粗体强调)。你知道吗

将其与表达式参考文档中的Slicings section进行比较;表达式中的切片生成^{} object,该list.__getitem__方法将其解释为对复制了匹配索引的新列表对象的请求。其他对象类型可以选择以不同的方式解释切片对象。你知道吗

注意,有一个第三个操作,^{} statement删除引用,包括切片。删除采用相同的target_list语法,并要求删除切片所指示的索引。你知道吗

这三个操作由^{}(读)、^{}(写)和^{}(删除)钩子方法实现;每个操作的key参数都是slice()对象,但只有__getitem__会返回任何内容。你知道吗

相关问题 更多 >