简体   繁体   中英

Negate all list values in a 2D array

The following two versions of my script work as intended:

matrix = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]]


def negate(amatrix):
    for alist in matrix:
        for i in range(len(alist)):
            alist[i] = -alist[i]
    return amatrix

print(negate(matrix))

Yields: [[-1, 2, -3], [4, -5, 6], [-7, 8, -9]]

as does this version:

matrix = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]]


def negate(amatrix):
    newmatrix = []
    for alist in amatrix:
        newlist = [-x for x in alist]
        newmatrix.append(newlist)
    return newmatrix

print(negate(matrix))

I am trying to use a comprehension to change the values in place, like the first version.

I have this:

matrix = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]]


def negate(amatrix):
    for alist in matrix:
        alist = [-x for x in alist]
    return amatrix

print(negate(matrix))

This third version does negate the individual values in each of the lists, but the changes are not saved in the matrix, ie, I want the list values changed in place.

Is there a way to use a comprehension to negate the individual list values in place, or do I have to use the indexed version (the first version above)?

List comprehensions do not work in place. When you say x = [-i for i in x] , the right hand side is evaluated first and assigned to x . Even if you are assigning it to the same variable, the solution is not in-place.

What you may want is a vectorised in-place solution. This is supported by numpy :

import numpy as np

arr = np.array([[1, -2, 3], [-4, 5, -6], [7, -8, 9]])

arr *= -1

# array([[-1,  2, -3],
#        [ 4, -5,  6],
#        [-7,  8, -9]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM