Green Tree Snakes使an example使用ExtSlice
:
>>> parseprint("l[1:2, 3]")
Module(body=[
Expr(value=Subscript(value=Name(id='l', ctx=Load()), slice=ExtSlice(dims=[
Slice(lower=Num(n=1), upper=Num(n=2), step=None),
Index(value=Num(n=3)),
]), ctx=Load())),
])
但是这种语法不能在交互式python shell中工作:
>>> foo = range(10)
>>> foo[1:2,3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
有人知道如何使用此功能吗?
相关讨论:
答案 0 :(得分:4)
语法在shell中运行良好,只是 list
个对象不支持扩展切片。您尝试的内容是TypeError
,而不是SyntaxError
。
许多Numpy数组类型都有;该项目有助于推动扩展切片语法。 Numpy数组使用扩展切片来解决多维数组的不同维度。有关如何使用语法的详细信息,请参阅Numpy Indexing chapter。
扩展切片为explicitly documented in the Subscription section,AST节点编码extended_slicing
项:
extended_slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= expression | proper_slice | ellipsis
proper_slice ::= short_slice | long_slice
然而,Python标准库本身没有使用扩展切片的类型。
您可以轻松构建自己的类来接受扩展切片;只希望在object.__getitem__()
method实施中处理一个元组:
>>> class Foo(object):
... def __getitem__(self, item):
... return item
...
>>> foo = Foo()
>>> foo[1, 2:3]
(1, slice(2, 3, None))
slice_list
的每个元素都成为元组中的一个对象,:
- 以[{1}}个实例传入的分隔切片索引。