简体   繁体   中英

Return a list of the sum of n integers in a list

I'm trying to write a function that will return a list that is made up of the sum of n integers in a list. I know that sounds confusing.

For example :

List = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

n = 5

the function should return [15,40,65]

I have a for loop created right now but it keeps using a preceding term that I don't want it to so the sum is always incorrect.

Any help would be appreciated!

Use a list comprehension and slicing:

>>> lis = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
>>> n = 5
>>> [sum(lis[i:i+n]) for i in xrange(0, len(lis), n)]
[15, 40, 65]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM