Python array multiply

后端 未结 3 1846
温柔的废话
温柔的废话 2020-12-20 12:14
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 typ

相关标签:
3条回答
  • 2020-12-20 13:06

    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]
    
    0 讨论(0)
  • 2020-12-20 13:07

    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]
    
    0 讨论(0)
  • 2020-12-20 13:12

    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]])
    
    0 讨论(0)
提交回复
热议问题