使用列表的Python扩展切片:文档正确吗?

2021-02-25 21:22:56 发布

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

位于http://docs.python.org/reference/expressions.html#slicings的文档说(有一些摘录):

5.3.3. Slicings

A slicing selects a range of items in a sequence object (e.g., a string, tuple or list).

slicing          ::=  simple_slicing | extended_slicing
simple_slicing   ::=  primary "[" short_slice "]"
extended_slicing ::=  primary "[" slice_list "]"
slice_list       ::=  slice_item ("," slice_item)* [","]
slice_item       ::=  expression | proper_slice | ellipsis
proper_slice     ::=  short_slice | long_slice
short_slice      ::=  [lower_bound] ":" [upper_bound]
long_slice       ::=  short_slice ":" [stride]
lower_bound      ::=  expression
upper_bound      ::=  expression
stride           ::=  expression
ellipsis         ::=  "..."

The semantics for a simple slicing are as follows. The primary must evaluate to a sequence object...

The semantics for an extended slicing are as follows. The primary must evaluate to a mapping object, ...

问题:

为了支持[1,2,3][a:b:c]符号,语言引用要求列表映射对象stride只有“扩展切片”才存在,这是用于映射对象的)。那么,语言引用是否中断了(可能他们只是在引入What's New in Python2.3: Extended Slices 时忘了更新它?)?在

此外,切片显然不仅仅适用于序列对象(参见上面的第一个短语)。在

还是只有我?;)

p.S.

有趣的是,python3文档在http://docs.python.org/release/3.1.3/reference/expressions.html#slicings上说:

A slicing selects a range of items in a sequence object (e.g., a string, tuple or list)...

["unified" slicing definition, not differentiating between "exteneded" and "simple" here]

The semantics for a slicing are as follows. The primary must evaluate to a mapping object, ...

2条回答
网友
1楼 ·

关于映射的语言是不完整的;它应该在所有情况下都说“序列或映射”,以匹配解释器的行为。这两种协议都可以接受slice对象,并且解释器在所有情况下都会进行转换。但是,对于内置类型,实际上只有序列支持它:

 >>> a = {'a': 1, 'c': 2}
 >>> a['a':'b']
 Traceback (most recent call last):
   File "<pyshell#32>", line 1, in <module>
     a['a':'b']
 TypeError: unhashable type: 'slice'

请注意,这是字典抱怨切片不是有效的键,而不是解释程序抱怨不能对映射执行切片。这是有道理的-字典没有隐含的键顺序,因此不清楚切片应该是什么意思。在

网友
2楼 ·

不幸的是,New和langref使用了“扩展切片”的两个不同定义。两份文件各自的定义都是正确的。在

相关问题