Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make this simple list comprehension?

I'm new to python, and I'm trying to get to know the list comprehensions better.
I'm not even really sure if list comprehension is the word I'm looking for, since I'm not generating a list. But I am doing something similar.

This is what I am trying to do:

I have a list of numbers, the length of which is divisible by three.

So say I have nums = [1, 2, 3, 4, 5, 6] I want to iterate over the list and get the sum of each group of three digits. Currently I am doing this:

for i in range(0, len(nums), 3):
    nsum = a + b + c for a, b, c in nums[i:i+3]
    print(nsum)

I know this is wrong, but is there a way to do this? I'm sure I've overlooked something probably very simple... But I can't think of another way to do this.

like image 760
Carson Myers Avatar asked Dec 22 '22 04:12

Carson Myers


1 Answers

See sum(iterable[, start]) builtin, and use it on slices.

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and are not allowed to be strings.

>>> nums
[1, 2, 3, 4, 5, 6]
>>> [sum(nums[i:i+3]) for i in  range(0, len(nums),3)]
[6, 15]
>>> 
like image 93
gimel Avatar answered Dec 24 '22 17:12

gimel