16
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]

???

3 Answers 3

21

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]
Sign up to request clarification or add additional context in comments.

4 Comments

how can I implement for 2 arrays ? see on EDIT 2
What exactly do you want? Do you want to multiply matrices (that is, the matrix product)? Do you want to multiply array elements by position? In both cases, I think you should check out numpy, for cleaner code.
yes matrix product; no I don't want to use numpy; please understand me
Yeah, I got it. Well, since matrix product is quite more complex and my math is a little rusty, I can't do a python implementation of that, but you can find some implementations of matrix product functions on Google, e.g.: syntagmatic.net/matrix-multiplication-in-python
8

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]

Comments

6

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]])

2 Comments

See the basic array operations for multiplication examples.
well i try not to use numpy or any other "library" which is not included while I installed IDE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.