您的位置:首页 > 编程语言 > Python开发

Python中的二维数组实例(list与numpy.array)

2018-12-13 14:46 357 查看

Python中的二维数组实例(list与numpy.array)

关于python中的二维数组,主要有list和numpy.array两种。

好吧,其实还有matrices,但它必须是2维的,而numpy arrays (ndarrays) 可以是多维的。

我们主要讨论list和numpy.array的区别:

{ a = [ [1, 2, 3],  [4, 5, 6] ] } 表示的是一个2*3的二维数组

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

1

2

3

4

5

6

7

8

9

10

11

12

13

>>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对应的索引输出情况:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

>>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对应的索引输出情况:

1

2

3

4

5

6

7

8

9

10

>>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])

由上面的简单对比可以看出, numpy.array支持比list更多的索引方式,这也是我们最经常遇到的关于两者的区别。此外从[Numpy-快速处理数据]上可以了解到“由于list的元素可以是任何对象,因此列表中所保存的是对象的指针。

这样为了保存一个简单的[1,2,3],有3个指针和3个整数对象。”

原文链接:https://www.geek-share.com/detail/2734584261.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: