在列表中添加两个连续的数字

use*_*345 4 python

如何在列表中添加两个连续的数字.

l = [1,2,3,4,5,6,7,8,9]
Run Code Online (Sandbox Code Playgroud)

结果= [3,7,11,15,9]

l = [1,2,3,4,5,6,7,8,9,10]
Run Code Online (Sandbox Code Playgroud)

结果= [3,7,11,15,19]

我可以使用简单的for循环轻松实现它.但是我如何使用更多的pythonic方式实现它.

eum*_*iro 13

import itertools as it    
[sum(r) for r in it.izip_longest(l[::2], l[1::2], fillvalue=0)]
Run Code Online (Sandbox Code Playgroud)

返回奇数和偶数的等待值:

l = [1,2,3,4,5,6,7,8,9]    # [3, 7, 11, 15, 9]
l = [1,2,3,4,5,6,7,8,9,10] # [3, 7, 11, 15, 19]
Run Code Online (Sandbox Code Playgroud)

更新:如果原始列表非常大,您可以将简单切片替换为islice:

[sum(r) for r in it.izip_longest(it.islice(l,0,None,2), it.islice(l,1,None,2), fillvalue=0)]
Run Code Online (Sandbox Code Playgroud)

更新2:即使是更短,更通用的版本(没有itertools)来到这里:

l = [1,2,3,4,5,6,7,8,9,10]
n = 3

[sum(l[i:i+n]) for i in xrange(0, len(l), n)]
# returns: [6, 15, 24, 10]
Run Code Online (Sandbox Code Playgroud)


JBe*_*rdo 6

您可以使用迭代器来避免中间列表:

>>> it = iter([1,2,3,4,5,6,7,8,9,10])
>>> [i + next(it, 0) for i in it]
[3, 7, 11, 15, 19]
Run Code Online (Sandbox Code Playgroud)

它也可以使用[1,2,3,4,5,6,7,8,9]因为next将返回零StopIteration.

  • 怎么样的呢?[i + next(it,0)for i in it]` (3认同)