Python 扩展切片与列表 : is the documentation correct?

标签 python list slice

文档位于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 时忘记更新它?)?

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

还是只有我这样? ;)

附注

有趣的是,Python 3 文档位于 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, ...

最佳答案

有关映射的语言已损坏;在所有情况下都应该显示“序列或映射”,以匹配解释器的行为。两种协议(protocol)都可以接受切片对象,并且解释器将在所有情况下进行转换。然而,对于内置类型,只有序列真正支持它:

 >>> 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'

请注意,这是字典提示切片不是有效键,而不是解释器提示您无法在映射上执行切片。这是有道理的 - 字典没有隐含的键顺序,因此不清楚切片的含义。

关于Python 扩展切片与列表 : is the documentation correct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6191765/

相关文章:

python - Pandas csv NaN 值替换为左侧列

python - 重命名多个文件夹内的多个文件

Python:具有相同名称的类和函数

python - .itemgetter 的奇怪输出,用于按值 python 进行列表排序

python - 根据 tensorflow 中给定的序列长度数组对 3D 张量进行切片

python - Python 中有没有内置的方法来检查单个列表索引

python - Jython 的 Numpy 模拟

python - 在 Python 中下载 Sharepoint Excel 文件

python - 将字符串列表提供给 sql 查询 [Python]

c# - list <T> : Clear; AddRange; Add; Delete; ect. 。导致 System.IndexOutOfRangeException