python && numpy : list VS np.array

直接上代码:

"""
list  是python的内置函数
array 是在numpy包中定义的

在应用中array比list具有更多的属性函数,使用更灵活,但是要求内部元素数据类型相同
list包容性更好,可以同时包含各种类型数据

-->如果是处理数字数据,建议将list转为np.array
"""

import numpy as np

a = [[1,2,3],[4,5,6]]
# a = [[1,2,3],[4,5,'t']]
b = np.array(a)

print('\n#####--data--#######')
print(a)   ## 列表不同元素间是“,”,输出 [[1, 2, 3], [4, 5, 6]]
print(b)   ## 列表不同元素间是“ ”空格,输出 [[1 2 3]
                                      ##  [4 5 6]]

print('\n#####--type--#######')
print(type(a)) ##<class 'list'>
print(type(b)) ##<class 'numpy.ndarray'>

print('\n#####--ndim--#######')
# print(a.ndim)
print(b.ndim)

print('\n#####--shape--#######')
# print(a.shape) ## AttributeError: 'list' object has no attribute 'shape'
print(b.shape)  ## (2, 3)

print('\n#####--reshape--#######')
# print(a.reshape) ## AttributeError: 'list' object has no attribute 'reshape'
print(b.reshape(1,3,2))

print('\n#####--dtype--#######')
# print(a.dtype) ## AttributeError: 'list' object has no attribute 'dtype'
print(b.dtype)  ## int64 

print('\n#####--len--#######')
print(len(a))  ## 2
print(len(b))  ## 2

print('\n#####--size--#######')
# print(a.size)  ## AttributeError: 'list' object has no attribute 'size'
print(b.size)    ## 6

print('\n#####--调用1--#######')
print(a[0])     ## [1, 2, 3]
print(b[0])     ## [1 2 3]

print('\n#####--调用2--#######')
print(a[0][:])   ## [1, 2, 3]
print(b[0][:])  ## [1 2 3]

print('\n#####--调用3--#######')
# print(a[0,:]) #TypeError: list indices must be integers or slices, not tuple
# print(a[0,1]) #TypeError: list indices must be integers or slices, not tuple
print(b[0,:])   ## [1 2 3]


print('\n#####--互相转换--#######')
b = np.array(a)
a_ = b.tolist()
print(a)
print(b)
print(a_)

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值