Python array multiply

60,915

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

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

Solution 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]])
Share:
60,915
thaking
Author by

thaking

Updated on July 13, 2020

Comments

  • thaking
    thaking almost 4 years
    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]
    

    ???

  • thaking
    thaking about 13 years
    how can I implement for 2 arrays ? see on EDIT 2
  • SiggyF
    SiggyF about 13 years
    See the basic array operations for multiplication examples.
  • thaking
    thaking about 13 years
    well i try not to use numpy or any other "library" which is not included while I installed IDE
  • Boaz Yaniv
    Boaz Yaniv about 13 years
    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.
  • thaking
    thaking about 13 years
    yes matrix product; no I don't want to use numpy; please understand me
  • Boaz Yaniv
    Boaz Yaniv about 13 years
    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