Carson Myers
Carson Myers

Reputation: 38564

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.

Upvotes: 4

Views: 263

Answers (3)

Harish
Harish

Reputation: 495

nums = [1, 2, 3, 4, 5, 6]
map(sum, itertools.izip(*[iter(nums)]*3))

Upvotes: 1

gimel
gimel

Reputation: 86344

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]
>>> 

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

import itertools

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

print [a + b + c for a, b, c in itertools.izip(*[iter(nums)] * 3)]

Upvotes: 4

Related Questions