[英]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]] 产量:[[-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
. 当您说
x = [-i for i in x]
,将首先评估右侧并将其分配给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
: 这受
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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.