1

我想连续乘以列表的相邻元素并添加乘法:

  • ([1,2,3,4])应该执行(1*2+2*3+3*4),并且
  • [1,2,3]我想得到8因为(1*2)+(2*3)
4

6 回答 6

3

使用pairwiseitertools 配方

>>> 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
于 2013-07-10T12:12:02.527 回答
3

使用列表理解:

>>> mylist = [1,2,3,4]
>>> sum(mylist[i] * mylist[i + 1] for i in range(len(mylist) - 1))
20
于 2013-07-10T12:03:04.753 回答
3

尝试这个:

x=[1,2,3,4]
print sum(a*b for a,b in zip(x, x[1:]))
#prints 20
于 2013-07-10T12:09:38.497 回答
1

sum使用,maplambda的函数zip

def my_math(lst):
    return sum(map(lambda x: x[0]*x[1], zip(lst,  lst[1:])))

>>> my_math([1,2,3])
8
>>> my_math([1,2,3,4])
20
>>> my_math([1,2,3,4,5])
40
于 2013-07-10T12:01:34.893 回答
0

没有任何列表切片/副本的生成器表达式

>>> mylist = [1,2,3,4]
>>> sum(mylist[i-1] * j for i, j in enumerate(mylist) if i)
20
于 2013-07-10T12:53:49.833 回答
0
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
于 2013-07-10T12:20:07.353 回答