Summing a 2D list

Mark markjturner at gmail.com
Thu Jun 12 10:15:35 EDT 2008


On Jun 12, 3:02 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> Mark wrote:
> > Hi all,
>
> > I have a scenario where I have a list like this:
>
> > User            Score
> > 1                 0
> > 1                 1
> > 1                 5
> > 2                 3
> > 2                 1
> > 3                 2
> > 4                 3
> > 4                 3
> > 4                 2
>
> > And I need to add up the score for each user to get something like
> > this:
>
> > User            Score
> > 1                 6
> > 2                 4
> > 3                 2
> > 4                 8
>
> > Is this possible? If so, how can I do it? I've tried looping through
> > the arrays and not had much luck so far.
>
> > Any help much appreciated,
>
> Show us your efforts in code so far. Especially what the actual data looks
> like. Then we can suggest a solution.
>
> Diez

Hi Diez, thanks for the quick reply.

To be honest I'm relatively new to Python, so I don't know too much
about how all the loop constructs work and how they differ to other
languages. I'm building an app in Django and this data is coming out
of a database and it looks like what I put up there!

This was my (failed) attempt:

predictions = Prediction.objects.all()
scores = []
for prediction in predictions:
	i = [prediction.predictor.id, 0]
	if prediction.predictionscore:
		i[1] += int(prediction.predictionscore)
	scores.append(i)

I did have another loop in there (I'm fairly sure I need one) but that
didn't work either. I don't imagine that snippet is very helpful,
sorry!

Any tips would be gratefully recieved!

Thanks,

Mark



More information about the Python-list mailing list