python中多个列表的产品总和

时间:2010-10-03 09:34:21

标签: python python-3.x algorithm

试图模仿Excel的SUMPRODUCT功能:

SUMPRODUCT(v1, v2, ..., vN) =
    v1[0]*v2[0]*...*vN[0] + v1[1]*v2[1]*...*vN[1] + ... + v1[n]*v2[n]*...*vN[n]

其中n是每个向量中元素的数量。

这类似于点积,但适用于多个向量。我阅读了常规点积的the very detailed discussion,但我不知道如何将它干净地扩展到多个向量。作为参考,我正在复制那里提出的优化代码,我将其(通常)移植到Python 3.BTW,对于dot产品,最后一种方法仍然在P3K中获胜。

def d0(v1,v2):
    """                                                                                                     
    d0 is Nominal approach:                                                                                 
    multiply/add in a loop                                                                                  
    """
    out = 0
    for k in range(len(v1)):
        out += v1[k] * v2[k]
    return out

def d1(v1,v2):
    """                                                                                                     
    d1 uses a map                                                                        
    """
    return sum(map(mul,v1,v2))

def d3(v1,v2):
    """                                                                                                     
    d3 uses a starmap (itertools) to apply the mul operator on an zipped (v1,v2)                           
    """
    return sum(starmap(mul,zip(v1,v2)))

3 个答案:

答案 0 :(得分:19)

import operator

def sumproduct(*lists):
    return sum(reduce(operator.mul, data) for data in zip(*lists))

for python 3

import operator
import functools

def sumproduct(*lists):
    return sum(functools.reduce(operator.mul, data) for data in zip(*lists))

答案 1 :(得分:7)

Map the list to create a list of products, and then sum it.

This can be done in one line:

        {

            ITime_2++; 

            try
            {
                Connect.Open();

                string Sql = "INSERT INTO Road_Record (Defined_Speed, Steering, Distance_Position, Road_Marking, Sign_Post) values ('" + Highway_Speed_Limit + "','" + Convert.ToInt32(Steering_Slider.Value) + "','" + (int)IDistance + "','" + Road_Markings + "','" + Highway_Signs + "')";

                using (SqlCommand cmdp = new SqlCommand(Sql, Connect))
                {
                    cmdp.ExecuteNonQuery();
                }

                Connect.Close();
            }

            catch (Exception ex)
            {
                Connect.Close();
                MessageBox.Show(ex.Message);
            }
        }

答案 2 :(得分:7)

良好的旧清单理解怎么样? (如@Turksarama所述,这仅适用于两个列表)

sum([x * y for x, y in zip(*lists)])

在Python 3.6中进行测试:

In [532]: import random

In [534]: x = [random.randint(0,100) for _ in range(100)]

In [535]: y = [random.randint(0,100) for _ in range(100)]

In [536]: lists = x, y

使用列表推导

In [543]: %timeit(sum([x * y for x, y in zip(*lists)]))
8.73 µs ± 24.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

请注意,“元组”理解为slower

In [537]: %timeit(sum(x * y for x, y in zip(*lists)))
10.5 µs ± 170 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

使用map

In [539]: %timeit(sum(map(lambda xi, yi: xi * yi, x, y)))
12.3 µs ± 144 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

使用functools.reduce

In [542]: %timeit(sum(functools.reduce(operator.mul, data) for data in zip(*lists)))
38.6 µs ± 330 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)