[英]Python Slice Notation with Comma/List
I have come across some python code with slice notation that I am having trouble figuring out. 我遇到了一些带有切片符号的python代码,但我很难弄清楚。 It looks like slice notation but uses a comma and a list:
它看起来像切片符号,但使用逗号和列表:
list[:, [1, 2, 3]]
Is this syntax valid? 这个语法有效吗? If so what does it do?
如果是这样,它怎么办?
edit looks like it is a 2D numpy array
编辑看起来像是一个2D numpy数组
Assuming that the object is really a numpy
array, this is known as advanced indexing , and picks out the specified columns: 假设该对象实际上是一个
numpy
数组,这称为高级索引 ,并选择指定的列:
>>> import numpy as np
>>> a = np.arange(12).reshape(3,4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> a[:, [1,2,3]]
array([[ 1, 2, 3],
[ 5, 6, 7],
[ 9, 10, 11]])
>>> a[:, [1,3]]
array([[ 1, 3],
[ 5, 7],
[ 9, 11]])
Note that this won't work with the standard Python list: 请注意,这不适用于标准的Python列表:
>>> a.tolist()
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
>>> a.tolist()[:,[1,2,3]]
Traceback (most recent call last):
File "<ipython-input-17-7d77de02047a>", line 1, in <module>
a.tolist()[:,[1,2,3]]
TypeError: list indices must be integers, not tuple
It generates a complex value and passes it to __*item__()
: 它生成一个复杂值并将其传递给
__*item__()
:
>>> class Foo(object):
... def __getitem__(self, val):
... print val
...
>>> Foo()[:, [1, 2, 3]]
(slice(None, None, None), [1, 2, 3])
What it actually performs depends on the type being indexed. 它实际执行的操作取决于所索引的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.