How do I make this simple list comprehension?
Posted
by Carson Myers
on Stack Overflow
See other posts from Stack Overflow
or by Carson Myers
Published on 2010-03-28T10:19:35Z
Indexed on
2010/03/28
10:23 UTC
Read the original article
Hit count: 480
python
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.
© Stack Overflow or respective owner