将 array
转成 list
比较简单,如下:
#array to list
array模块,但其只支持一维数组,不支持多维数组,也没有各种运算函数。
import numpy as np
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) Cell In[3], line 1 ----> 1 import numpy as np ModuleNotFoundError: No module named 'numpy'
这样定义的数组时list object,可以拿list当数组用
#matrix=[0 for i in range(4)]
matrix_array=np.random.randint(0,3,(2,3))
其他定义:
可以用于预先申请内存
#array = np.empty((5, 4), dtype=int)
matrix_list = matrix_array.tolist()
运行将 list
转换成数组。
由于 list
中可以存放不同类型的元素,因此在转换成数组时,
为了保证转换不出错,要检查类型是否一致,有数字且有字符的 list
转成 array
时会变成字符数组。
import numpy as np
# define list
array = np.asarray(list)
#the second method
array = np.array(list, dtype = np.int32)
list
对象的常用方法有:
list=[1,2,3,4,5]
#list的定义以[]
方式,tuple的定义以()
方式list.insert(1, 'content')
#在指定位置插入元素list.pop()
#将最后一位的元素删除list.pop(i)
#删除指定位置的元素,i从0开始list[-1]
#下标访问
下面介绍一个快速的将 list
转换成 array
的函数,代码来自 TSN_ECCV2016
,如下:
def fast_list2arr(data, offset=None, dtype=None):
"""
Convert a list of numpy arrays with the same size to a large numpy array.
This is way more efficient than directly using numpy.array()
See
https://github.com/obspy/obspy/wiki/Known-Python-Issues
:param data: [numpy.array]
:param offset: array to be subtracted from the each array.
:param dtype: data type
:return: numpy.array
"""
num = len(data)
out_data = np.empty((num,)+data[0].shape, dtype=dtype if dtype else data[0].dtype)
for i in xrange(num):
out_data[i] = data[i] - offset if offset else data[i]
return out_data
代码解读
运行运行
该方法中每个元素都是 array
,但是整个对象是 array list
,
要转换成 array of array
才能送入 caffe
网络进行预测。
原理是先申请空间再逐一复制 array list
中的每个元素。
a = list([1,2,3,4])
a
import array
b = array.array('i', a)
b
list
和 array
区别
列表(list
)
列表( list
)是Python内置的数据结构,它拥有很多重要的特性。
适用场景: 保存序列、迭代、递归。
- 列表的基本形式 -> 如
[item1, item2, itme3]
- 列表是有序的 -> 即列表中项目以特定顺序显示,可使用索引来使用任何项目
- 列表是可变的 -> 意味着可以创建列表后进行添加或删除列元素
- 列表元素不唯一 -> 意味着可以有相同的元素在一个列表中,每个元素有自己独立的存储空间且通过索引进行访问
- 列表元素可以是不同的数据类型 -> 意味着可以在一个列表中组合多种类型的元素
数组(array
)
一个数组也是一个数据结构,在Python中使用数组的话,
需要导入 array
或 NumPy
的包。
特性与列表类似:
- 有序的
- 可变的
- 基本形式为方括号
- 不唯一
注意的是,Python中的数组模块需要所有数组元素都具有相同类型。