一、list和array的区别
Python的数组通过Numpy包的array实现。
Python里二者最大的区别是,list可以存储不同类型的数据,而array只能存储相同类型的数据。
import numpy
#直接定义
a = [1,2,3,4,'5'] #列表list,可以混合类型
b = numpy.array([1,2,3,4,5]) #数字数组array
c = numpy.array([1,2,3,4,'5']) #字符数组array
#打印出来也有不同
print(a) #[1, 2, 3, 4]
print(b) #[1 2 3]
print(c) #['1' '2' '3' '4' '5']
#生成值为连续数字的对象
a1 = list(range(5))
b1 = numpy.arange(5)
#打印结果
print(a1) #[0, 1, 2, 3, 4]
print(b1) #[0 1 2 3 4]
二、创建数组的方法
(一) numpy.empty 创建未初始化的数组(非空,元素为随机值)
numpy.empty(shape, dtype = float, order = ‘C’)
参数列表分别为形状,数据类型,在计算机中的存储为行优先 ‘C’ 或者列优先 ‘F’。
import numpy
x = numpy.empty([3,2], dtype = int)
print(x)
[[0 0]
[0 0]
[0 0]]
(二) numpy.zeros 创建元素为 0 的数组
numpy.zeros(shape, dtype = float, order = ‘C’)
import numpy
y = numpy.zeros((2,2), dtype=