使用“Reduce”的列表中的平方根乘积

Products of square roots in a list using `Reduce`

假设我想计算 List 中每个元素的平方根的乘积。 在 Java like

中也可以实现同样的效果
import java.util.ArrayList;

public class App {
    public static void main(String[] args) {

        ArrayList<Double> arrays = new ArrayList<>();
        arrays.add(4.0);
        arrays.add(9.0);
        arrays.add(16.0);

        double i = arrays.stream().reduce(1.0, (a, b) -> (a * Math.sqrt(b)),
                                                         (a, b) -> (a * b));
        System.out.println(i);

    };
}

输出:

24.0

如何在 Python 中实现同样的效果。下面给出不正确的。

  >>> reduce(lambda a,b: math.sqrt(a)*math.sqrt(b), [4,9,16])
  9.797958971132712

因为它等同于

>>> math.sqrt(math.sqrt(4)*math.sqrt(9))*math.sqrt(16)

然而 Java 中相同的语法给出不同的结果。它是如何计算的?

double i = arrays.stream().reduce(1.0, (a, b) -> (Math.sqrt(a) * Math.sqrt(b)));

输出:

8.23906857562847

你需要提供初始值来实现与java中相同的逻辑,这里第一个参数x作为累加值,由1初始化:

from functools import reduce
from math import sqrt 

reduce(lambda x, y: x * sqrt(y), [4,9,16], 1)
# 24.0

如果您不提供初始值,它将从序列中的第一个元素开始。

有了初始值,这应该等同于您最后一个 java 示例:

reduce(lambda x, y: sqrt(x) * sqrt(y), [4,9,16], 1)
# 8.23906857562847