Lists of lists traversal
Kaleissin
kaleissin at nvg.org
Mon Dec 20 16:17:27 EST 1999
In article <83m3fn$sb6$1 at cronkite.cc.uga.edu>, Benjamin Dixon wrote:
>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
>
>and other stuff but I'm not certain as to how to reference a specific
>member of a given sublist.
If I understand you correctly... you want to 'compress' the inner lists
and replace them with their sums?
If that is the case...
Summing a list:
result = reduce(lambda x, y: x+y, list_to_sum)
What I would do in your case:
listpos = 0
while listpos < len(list_of_lists):
list_of_lists[listpos] = reduce(lambda x, y: x+y, list_of_lists[listpos])
listpos = listpos + 1
This destroys the original lists btw. To keep them, append the resulting
sum to some other list instead of replacing the list with it as above.
You could use a for instead of the while too, in that case.
It might not be very effective but it looks nice... list comprehension
version, anyone?
kal.
--
Teflon Brain 2000(tm) - Excuse of the Future!
More information about the Python-list
mailing list