I have some problem which has stumped my beginner-knowledge of python and I hope someone out there can point me in the correct direction.
I generated a nested list, each
Here's a variation on m170897017's technique:
a = [[1, 0],[1, 2],[2, 9],[3, 0],[3, 8],[3, 1]]
result = {}
for day, val in a:
if day not in result:
result[day] = 0
result[day] += val
print result
#Convert back into a list
print [list(t) for t in result.items()]
output
{1: 2, 2: 9, 3: 9}
[[1, 2], [2, 9], [3, 9]]
If you're using Python 2.7 or later, you could also use a Counter.
Another possibility is to use a defaultdict, which has been available since Python 2.5.
from collections import defaultdict
a = [[1, 0],[1, 2],[2, 9],[3, 0],[3, 8],[3, 1]]
result = defaultdict(int)
for day, val in a:
result[day] += val
print [list(t) for t in result.items()]
output
[[1, 2], [2, 9], [3, 9]]