在 python 中,这个带有括号内未定义项的 for 循环是什么意思?

What does this for loop with undefined terms inside brackets mean in python?

我在 python 中有一个数学代码,需要将其转换为 java。但我不知道如何操作:

#python source
sum([d**2 for d in (x - y)])

x,y 是数组,已定义且具有值。我在 for 循环以及该循环中与 d^2d 的连接方面遇到问题。

括号中的实际for循环是一个list comprehension,它生成一个列表。通常,这表示如下:

[ expression( <variables> ) for <variables> in <list> ]

这意味着您的变量(此处 d)将迭代给定列表(此处 (x - y))中的值。返回的列表将包含表达式的值,为 d.

的每个值计算

这种写法是在变量使用后才定义的,没见过定义是正常的。

明确地说,代码等价于以下内容:

squares = []
for d in (x - y):
    squares.append(d**2)
sum(squares)

平凡地,sum returns 列表的总和。


因为你说你的代码在做数学运算而且你说的是 arrays 而不是 lists,我从这里假设你意味着 x,y 是 numpy 数组。

在这种情况下,x - y的含义是:数组的逐项减法。
写成列表理解,它看起来像:[a - b for a,b inzip(x,y)]

因此 python 重写该代码可以是:

sum = 0
for a,b in zip(x,y):
    sum += (a - b) * (a - b)

或仅使用 numpy 函数:

numpy.square(x - y).sum()