使用python做了一个应用,结果是不定长的,所以用了列表类型:
a=[]
a.append(3.1)
a.append(5.2)
......
使用help(a)可知,a为列表(List)对象
如果直接对a做运算,会产生以下结果:
>>> a+0.2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "float") to list
>>> a-0.2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'float'
>>> a*0.2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
>>> a/0.2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'list' and 'float'
需要将a转换为数组(Array)对象再进行运算操作:
>>>import numpy as np
>>> b=np.array(a)
>>> b
array([3.1, 5.2])
>>> b+0.2
array([3.3, 5.4])
>>> b-0.2
array([2.9, 5. ])
>>> b*0.2
array([0.62, 1.04])
>>> b/0.2
array([15.5, 26. ])
结论:Python中,List类型适合动态添加、删除元素,但不能直接进行运算。Array类型可直接参与运算,但添加、删除元素时,需要使用np.append()和np.delete()等操作,相当于重新创建了数组。