我想连续乘以列表的相邻元素并添加乘法:
([1,2,3,4])
应该执行(1*2+2*3+3*4)
,并且[1,2,3]
我想得到8
因为(1*2)+(2*3)
>>> sum(a * b for (a, b) in pairwise([1, 2, 3, 4]))
20
>>> sum(a * b for (a, b) in pairwise([1, 2, 3]))
8
如果要
function([1,2,3,4])
执行,我需要更改什么(1*2*3*4)
?
>>> from functools import reduce
>>> from operator import mul
>>> reduce(mul, [1, 2, 3, 4])
24
使用列表理解:
>>> mylist = [1,2,3,4]
>>> sum(mylist[i] * mylist[i + 1] for i in range(len(mylist) - 1))
20
尝试这个:
x=[1,2,3,4]
print sum(a*b for a,b in zip(x, x[1:]))
#prints 20
没有任何列表切片/副本的生成器表达式
>>> mylist = [1,2,3,4]
>>> sum(mylist[i-1] * j for i, j in enumerate(mylist) if i)
20
In [88]: mylist = [1,2,3,4]
In [89]: sum(itertools.imap(lambda t: operator.mul(*t), itertools.izip(mylist, itertools.islice(mylist, 1, len(mylist)))))
Out[89]: 20