本文介绍了带有逗号/列表的Python切片符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了一些带有切片符号的python代码,但我很难弄清楚.看起来像切片符号,但使用逗号和列表:
I have come across some python code with slice notation that I am having trouble figuring out.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?
编辑看起来像是一个二维的numpy数组
edit looks like it is a 2D numpy array
推荐答案
假定对象确实是一个numpy
数组,则称为高级索引,并选择指定的列:
Assuming that the object is really a numpy
array, this is known as advanced indexing, and picks out the specified columns:
>>> 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]])
请注意,这不适用于标准的Python列表:
Note that this won't work with the standard Python list:
>>> 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
这篇关于带有逗号/列表的Python切片符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!