相邻元素相乘

2 投票
5 回答
2654 浏览
提问于 2025-04-17 16:08

我有一个整数的元组,比如 (1, 2, 3, 4, 5),我想通过相邻的元素相乘来生成一个新的元组 (1*2, 2*3, 3*4, 4*5)。请问有没有办法用一行代码做到这一点?

5 个回答

3

我喜欢这个叫做itertools的库里的例子

from itertools import izip, tee

def pairwise(iterable):
    xs, ys = tee(iterable)
    next(ys)
    return izip(xs, ys)

print [a * b for a, b in pairwise(range(10))]

结果:

[0, 2, 6, 12, 20, 30, 42, 56, 72]
6
>>> t = (1, 2, 3, 4, 5)
>>> print tuple(t[i]*t[i+1] for i in range(len(t)-1))
(2, 6, 12, 20)

这不是最符合Python风格的解决方案。

10

简单明了。记住,zip 这个功能只会运行到最短的输入为止。

print tuple(x*y for x,y in zip(t,t[1:]))

撰写回答