Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding two consecutive numbers in a list

Tags:

python

How to add two consecutive number in the list.

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

result = [3,7,11,15,9]

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

result = [3,7,11,15,19]

I can easily achieve it using simple for loop. But How can I achieve it using more pythonic way.

like image 528
user12345 Avatar asked Nov 29 '22 17:11

user12345


1 Answers

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

returns awaited values for both odd and even numbers:

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]

UPDATE: if the original list is really large, you can replace the simple slices with islice:

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

UPDATE 2: even a shorter and more universal version (without itertools) comes here:

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]
like image 50
eumiro Avatar answered Dec 06 '22 19:12

eumiro