[Tutor] Averaging a list of lists with a listcomp?
Terry Carroll
carroll at tjc.com
Thu Apr 26 05:58:20 CEST 2007
I have a list (of arbitrary length) of lists, each sublist having a fixed
number N of items, all integers.
I would like to produce a list of N items, each item of which is an
integer which is the average of the elements in the same position of each
of the sublists of the original list.
I realize the wording above is all hash, so here's the example:
Say the original list is: [[10, 20, 30], [50, 20, 90], [30, 20, 30]]
I want the new list to be: [30, 20, 50]
Because the average of the first elements 10, 50, 30 is 30; second
elements 20, 20, 20 is 20; and third elements 30, 90, 30 is 50.
Since I'm taking a list and producing another list, I figured this would
be a good candidate for a list comprehension; but I don't see a good
approach.
My attempt is below, but I can see the list comp approach is pretty yucky.
As you can see, I've got a working solution, but in an effort to think
more pythonically about list comprehensions, I'd like to see what a good
list comprehension approach is.
(note: I know there's an integer division issue here; ignore that, I just
picked easy numbers to keep the example clean.)
My approach:
###################################
orig = [[10, 20, 30], [50, 20, 90], [30, 20, 30]]
average = [30, 20, 50]
# iterative approach
L1 = [0, 0, 0]
for item in orig:
for i in range(0,3):
L1[i] += item[i]
L1 = [x/len(orig) for x in L1]
print L1
#list comp approach
L2 = [
sum([x[0] for x in orig])/len(orig),
sum([x[1] for x in orig])/len(orig),
sum([x[2] for x in orig])/len(orig)
]
#ew, yuck, hard-coded list indices!
print L2
assert L1 == L2 == average
###################################
More information about the Tutor
mailing list