加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Python中访问数组列的最佳方法是什么?

发布时间:2020-12-20 13:05:43 所属栏目:Python 来源:网络整理
导读:在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 moduleTypeError: list indi
在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>",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(:,:)

ans(:,1) =

     0
     1
     0


ans(:,2) =

     1
     1
     1


ans(:,3) =

     1
     5
     9

解决方法

使用 Numpy.

>>> import numpy as np
>>> 
>>> a = np.array([[1,6]])
>>> a[:,2]
array([3,6])

如果你来自Matlab,那应该是有意义的:http://www.scipy.org/NumPy_for_Matlab_Users

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读