tags:

views:

104

answers:

3

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.

+4  A: 
import itertools

nums = [1, 2, 3, 4, 5, 6]

print [a + b + c for a, b, c in itertools.izip(*[iter(nums)] * 3)]
Ignacio Vazquez-Abrams
awesome, thank you!
Carson Myers
Does your solution have any advantage compared to `sum()` and sublists (execution time, memory)? I am just curious ;)
Felix Kling
@Felix: Not really, no.
Ignacio Vazquez-Abrams
+6  A: 

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]
>>> 
gimel
+1 exactly my thought but you were faster and your answer is more elaborated :)
Felix Kling
wow, would have never thought of this, perfect
Carson Myers
actually, I get this error: `TypeError: sequence index must be integer, not 'slice'`
Carson Myers
@Carson Myers did you type it exactly like above, no brackets placed differently? What python version do you use?
extraneon
The "sequence" in that exception makes me think that it's some custom sequence that doesn't support slicing.
Ignacio Vazquez-Abrams
You would get that exception for `nums=xrange(1,7)`
gnibbler
ooohhhhhh, I was using a deque :/ I have to change it to a list
Carson Myers
+2  A: 
nums = [1, 2, 3, 4, 5, 6]
map(sum, itertools.izip(*[iter(nums)]*3))
Harish