Search code examples
pythonarrayslist2dmultiplication

How do you multiply every element inside a 2D array by -1?


I have a 2D array filled with values. To multiply every element inside a 1D array, you can use list comprehensions. Yet I'm uncertain how to formulate the list comprehension to work over a 2D array.

R = [[0, 0.94, 0.91, 0.96, 0.93, 0.92],
    [0.94, 0, 0.94, 0.97, 0.91, 0.92],
    [0.91, 0.94, 0, 0.94, 0.90, 0.94],
    [0.96, 0.97, 0.94, 0, 0.93, 0.96],
    [0.93, 0.91, 0.90, 0.93, 0, 0.91],
    [0.92, 0.92, 0.94, 0.96, 0.91, 0]]

RNeg = [[i*(-1) for i in R]]

How do I fix RNeg to perform the correct operation?


Solution

  • numpy.array(R) * -1
    

    is the easiest

    if you have to do it by hand

    [[val*-1 for val in row] for row in R]