对于内建,可以使用zip将位于同一索引位置的元素组合在一起list1 = [2,3,4]
list2 = [3,3,3]
result = sum( x*y for x,y in zip(list1, list2) )
关于编辑
内置版本应该是
^{pr2}$
更普遍的说法是
import operator
def dotproduct(vec1, vec2, sum=sum, map=map, mul=operator.mul):
return sum(map(mul, vec1, vec2))
你可以为它的任何部分提供你喜欢的任何功能,那么第一个是result = dotproduct(list1,list2)
第二个可能是result = dotproduct(range(1,len(list1)+1),list1, mul=lambda i,x:log(i)*x )
# ^ the i ^ how to operate
或者result = dotproduct(map(log,range(1,len(list1)+1) ), list1 )
# ^ the log i
关键是你要相应地计算第二个向量
有了numpy就更容易了import numpy as np
logi = np.log(np.arange(1,len(list1)+1)
result = np.dot(logi,list1)
这又归结为相应地计算各部分
您还可以使它不接收2个向量/列表,而只接收一个向量/列表,并接收一个在元素及其索引中工作的函数
def sum_serie(vect, fun = lambda i,x:x, i_star=0): #with that fun, is like the regular sum
return sum( fun(i,x) for i,x in enumerate(vect, i_star) )
把它当作result = sum_serie( list1, lambda i,x:log(i)*x, 1)
从评论来看,如果我做对了,那么就这样吧from itertools import islice
def sum_serie(vect, *slice_arg, fun = lambda x:x): #with that fun, is like the regular sum
"""sum_serie(vect, [start,]stop[,step], fun = lambda x:x)"""
if not slice_arg:
slice_arg = (0,None,None)
return sum( fun(x) for x in islice(vect, *slice_arg) )
或者像以前一样枚举from itertools import islice
def sum_serie_i(vect, *slice_arg, fun = lambda i,x:x): #with that fun, is like the regular sum
if not slice_arg:
slice_arg = (0,None,None)
return sum( fun(i,x) for i,x in islice(enumerate(vect), *slice_arg) )
使用,例如sum_serie( x, 0, 100, 2, fun=lambda xi: c*xi) #for arbitrary constant c
sum_serie_i( x, 0, 100, 2, fun=lambda i,xi: log(i)*xi)
注意:这样它接受serie/iterable/whatever,最多3个位置参数,其含义与range中的参数相同
注2:对于PY3来说,它只是一个关键字参数,在python2中,同样的效果是通过def sum_serie_i(vect, *slice_arg, **kargv):
fun = kargv.get('fun', lambda i,x:x) #with that fun, is like the regular sum
if not slice_arg:
slice_arg = (0,None,None)
return sum( fun(i,x) for i,x in islice(enumerate(vect), *slice_arg) )