Summing a 2D list

Diez B. Roggisch deets at
Thu Jun 12 16:31:47 CEST 2008

> 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 = [, 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!

It is helpful because it tells us what your actual data looks like. 

What you need is to get a list of (predictor, score)-pairs. These you should
be able to get like this:

l = [(, p.predictionscore) for p in predictions]

Now you need to sort this list - because in the next step, we will aggregate
the values for each predictor.

result = []
current_predictor = None
total_sum = 0
for predictor, score in l:
    if predictor != current_predictor:
       # only if we really have a current_predictor, 
       # the non-existent first one doesn't count
       if current_predictor is not None:
           result.append((predictor, total_sum))
       total_sum = 0
       current_predictor = predictor
    total_sum += score

That should be roughly it.


More information about the Python-list mailing list