列表list、数组np.array等的len,size,shape操作

本菜最近师命难违,在别人享受大四生活的同时不得不学习代码,搞搞DL。python基础差实在是难受,本菜记忆力和金鱼差不多,故写下这些小知识点以便常常复习之用,希望大佬看到不要踩我

参考原博:https://blog.csdn.net/Alicehzj/article/details/78686293


python中常见的二维数组有list与numpy.array。在很多情况下我们需要获取数组的大小,阅读过一些python代码可以发现,常见的方法一般有len, size, shape这三种,那么这三种方法分别应用于那些场合?有什么区别?

import numpy as np
a = [[1,2,3,4], [5,6,7,8], [9, 10, 11, 12]]
b = np.array(a)
print type(a)
print a
print type(b)
print b



[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

list

list---len

print len(a), len(a[0])


3 4

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
 in ()
      1 print len(a), len(a[0])
----> 2 print size(a)

NameError: name 'size' is not defined

list---size

print size(a)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
 in ()
----> 1 print size(a)

NameError: name 'size' is not defined


In [6]:
print a.size


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
 in ()
----> 1 print a.size

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

list---shape

print shape(a)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
 in ()
----> 1 print shape(a)

NameError: name 'shape' is not defined



In [8]:
print a.shape


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
 in ()
----> 1 print a.shape

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

由上可知,list只支持len(), 该方法实际是调用了对象的len(self)方法

numpy.array

对比之下,numpy.array同时支持len, size, shape, 注意看三者返回值的区别。

此外,numpy中还提供matrix的数据类型,具体请看:

c = np.mat(a)
print type(c)
print c
d = np.mat(b)
print type(d)
print d
print len(d)
print d.size
print d.shape



[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
3
12
(3, 4)

从上面的例子可以看出,martix支持由list和numpy.array创建,同时支持len, size以及shape.

你可能感兴趣的:(列表list、数组np.array等的len,size,shape操作)