python - Summing groups of items in a list -


list1 = [1,3,5,7,9,11,13,15,17] list2 = [] 

i want add 3 first elements list2[0] , next 3 list2[1] , on.

1+3+5 list2[0] 7+9+11 list2[1] 13+15+17 list2[2] 

the result should be:

list2 = [9,27,45] 

the documentation standard itertools module has recipe dividing list fixed-length groups:

def grouper(iterable, n, fillvalue=none):     "collect data fixed-length chunks or blocks"     # grouper('abcdefg', 3, 'x') --> abc def gxx"     args = [iter(iterable)] * n     return zip_longest(*args, fillvalue=fillvalue) 

as beginner, might not understand how works, did confirm does:

import itertools  def grouper(iterable, n, fillvalue=none):     "collect data fixed-length chunks or blocks"     # grouper('abcdefg', 3, 'x') --> abc def gxx"     args = [iter(iterable)] * n     return it.zip_longest(*args, fillvalue=fillvalue)  list1 = [1,3,5,7,9,11,13,15,17] print(list(grouper(list1, 3))) 

prints: [(1, 3, 5), (7, 9, 11), (13, 15, 17)]. have tuples of each 3 items, need add them up, builtin sum for:

list2 = [sum(group) group in grouper(list1, 3)] 

if list length isn't divisible 3, break error this:

typeerror: unsupported operand type(s) +: 'int' , 'nonetype' 

which can fixed in 1 of 2 ways: if want ignore odd elements, change grouper call zip calls it.zip_longest; on other hand, if want final element in list2 sum of odd elements, use fill value of 0 this:

list2 = [sum(group) group in grouper(list1, 3, 0)] 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -