如何在Python中实现一个二维数组

今天就跟大家聊聊有关如何在Python中实现一个二维数组,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

list和numpy.array的区别:

我们可以通过以下的代码看出二者的区别

>>import numpy as np
>>a=[[1,2,3],[4,5,6],[7,8,9]]
>>a
[[1,2,3],[4,5,6],[7,8,9]]
>>type(a)
<type 'list'>
>>b=np.array(a)"""List to array conversion"""
>>type(b)
<type 'numpy.array'>
>>b
array=([[1,2,3],
    [4,5,6],
    [7,8,9]])

list对应的索引输出情况:

>>a[1][1]
5
>>a[1]
[4,5,6]
>>a[1][:]
[4,5,6]
>>a[1,1]"""相当于a[1,1]被认为是a[(1,1)],不支持元组索引"""
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
>>a[:,1]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple

numpy.array对应的索引输出情况:

>>b[1][1]
5
>>b[1]
array([4,5,6])
>>b[1][:]
array([4,5,6])
>>b[1,1]
5
>>b[:,1]
array([2,5,8])

看完上述内容,你们对如何在Python中实现一个二维数组有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。