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

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

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.

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值