# Python——“元组、列表、字典、数组和矩阵”的大小问题

### （1）数组和矩阵的大小

import numpy as np

A = np.random.randint(1,100,size = (4,5))
A
array([[56, 96, 27, 38, 33],
[86, 64, 52, 21, 66],
[97, 84, 94, 20, 82],
[65, 17, 77,  9, 17]])

B = np.random.randint(1,100,size = (1,5))
B
array([[66, 90, 49, 75, 11]])


1）使用size方法/函数

• 数组用例
A.size         #数组A是4行5列，即总共20个元素
20

np.size(A)    
20

len(A)        #如果采用len()是无法获取整个数组或者矩阵的元素个数的。但是可以计算数组的行数，相当于A.shape[0]
4

A.shape[0]
4

• 矩阵用例
C = np.mat(A)
C
matrix([[56, 96, 27, 38, 33],
[86, 64, 52, 21, 66],
[97, 84, 94, 20, 82],
[65, 17, 77,  9, 17]])

C.size
20

np.size(C)
20

len(C)
4


### （2）列表的大小

import numpy as np

D = [1,2,3,4,5]
D
[1, 2, 3, 4, 5]

D.size
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-31-0fe167b3857b> in <module>()
----> 1 D.size

AttributeError: 'list' object has no attribute 'size'

np.size(D)     
5

len(D)
5


### （3）元组的大小

import numpy as np

E = (1,2,3,4,5)
E
(1, 2, 3, 4, 5)

E.size
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-35-1a7fda531ae5> in <module>()
----> 1 E.size

AttributeError: 'tuple' object has no attribute 'size'

np.size(E)
5

len(E)
5


### （4）字典的大小

import numpy as np

A = {"a":1,"b":2,"c":3,"d":4}    #包含4个键值对
A
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

A.size
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-5-0c1207b28e02> in <module>()
----> 1 A.size

AttributeError: 'dict' object has no attribute 'size'

np.size(A)         #无法获取字典的大小
1

len(A)             #len(A)可以正确获取字典大小
4