Python array multiply

拟墨画扇 提交于 2019-11-29 13:21:32

When you multiply a sequence by X in Python, it doesn't multiply each member of the sequence - what it does is to repeat the sequence X times. That's why X has to be an integer (it can't be a float).

What you want to do is to use a list comprehension:

hh = [[82.5], [168.5]]
N  = 1.0 / 5
ll = [[x*N for x in y] for y in hh]

Well in Python you can do this:

>>> [2] * 3
[2, 2, 2]

This requires an int type.

What you are looking for is something a kin to map or a list comprehension.

>>> list(map(lambda x: x * 2, [2, 2]))
[4, 4]
>>> [x * 2 for x in [2, 2]]
[4, 4]

You can also generator comprehension to do it lazily.

(x * 2 for x in [2, 2])

Or you can do it a bit Haskellish (albeit without the elegance):

>>> import operator
>>> from functools import partial, reduce
>>> add = partial(operator.mul, 2)
>>> list(map(add, [2,2]))
[4, 4]
SiggyF

You can also use the numpy array for multiplying the numbers in the array.

>>> hh = numpy.asarray([[82.5], [168.5]])
>>> N = 1.0/5
>>> ll = N*hh
>>> ll
array([[ 16.5],
       [ 33.7]])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!