问题
hh=[[82.5], [168.5]]
N=1./5
ll=N*hh
What I'm doing wrong? I received error :
"can't multiply sequence by non-int of type 'float'"
I try to add float(), but this is not solve my problem;
I need to multiply each element in array... thanks to all
**Ok thanks for idea for number * array, but how to multiply array*array, I tried same as number*array, but have problems:
EDIT 2:**
hh=[[82.5], [168.5]]
N=zip(*hh)
ll = [[x*N for x in y] for y in hh]
???
回答1:
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]
回答2:
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]
回答3:
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]])
来源:https://stackoverflow.com/questions/5825208/python-array-multiply