Lists of lists traversal
Justin Sheehy
dworkin at ccs.neu.edu
Wed Dec 22 16:45:22 EST 1999
"Benjamin Dixon" <beatle at arches.uga.edu> writes:
> Hello, I am new to Python and am trying to figure out how I can iterate
> over a list that I know to contain other lists of integers so that I can
> add up the individual lists inside the larger list.
>
> I tried things like this:
>
> Sum(input):
> for x in input:
> value = 0
> for y in input:
> value = value + y
> return y
Your description above doesn't give me a very clear idea of what you
are trying to do. The following function, given a list of lists of
numbers, will return a list of their sums:
>>> def Sum(ls):
... from operator import add
... newls = []
... for i in ls:
... newls.append(reduce(add, i))
... return newls
...
>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> Sum(l)
[6, 15, 24]
Perhaps from there you can find a way to solve whatever problem you
are trying to solve.
-Justin
More information about the Python-list
mailing list