Summing a 2D list
MRAB
google at mrabarnett.plus.com
Sat Jun 14 17:15:10 EDT 2008
On Jun 14, 4:05 pm, sturlamolden <sturlamol... at yahoo.no> wrote:
> On Jun 12, 3:48 pm, Mark <markjtur... at gmail.com> wrote:
>
> > Is this possible?
>
> def foobar(user,score):
> sums = {}
> for u,s in zip(user,score):
> try:
> sums[u] += s
> except KeyError:
> sums[u] = s
> return [(u, sums[u]) for u in sums].sort()
>
sort() sorts the list in-place and returns None. Try this instead:
return sorted([(u, sums[u]) for u in sums])
or, better yet:
return sorted(sums.items())
> usersum = foobar(user,score)
> for u,s in usersum:
> print "%d %d" % (u,s)
More information about the Python-list
mailing list