在 Matlab 中,可以使用 :
访问数组的列:
>> array=[1 2 3; 4 5 6]
array =
1 2 3
4 5 6
>> array(:,2)
ans =
2
5
如何在 Python 中执行此操作?
>>> array=[[1,2,3],[4,5,6]]
>>> array[:,2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
>>> array[:][2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
附录
我想要一个应用于维度大于三的数组的示例:
>> B = cat(3, eye(3), ones(3), magic(3))
B(:,:,1) =
1 0 0
0 1 0
0 0 1
B(:,:,2) =
1 1 1
1 1 1
1 1 1
B(:,:,3) =
8 1 6
3 5 7
4 9 2
>> B(:,:,1)
ans =
1 0 0
0 1 0
0 0 1
>> B(:,2,:)
ans(:,:,1) =
0
1
0
ans(:,:,2) =
1
1
1
ans(:,:,3) =
1
5
9
最佳答案
使用Numpy .
>>> import numpy as np
>>>
>>> a = np.array([[1,2,3],[4,5,6]])
>>> a[:, 2]
array([3, 6])
如果您来自 Matlab,这应该会引起您的兴趣:Link
关于python - 在 Python 中访问数组列的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8900288/