how to add the numbers of a list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: how to add the numbers of a list (/thread-17334.html) |
how to add the numbers of a list - Pedroski55 - Apr-07-2019 I have a list. Each element is either 1 or 0. I want to add them sequentially. For example: I have: attendance = [1, 1, 1, 1] I declare: cumulativeAttendance = [0] to start with, otherwise I get index errors. cumulativeAttendance[1] is cumulativeAttendance[0] + attendance[0] then cumulativeAttendance[1] = cumulativeAttendance[0] + attendance[1] cumulativeAttendance = [0, 1, 2, 3, 4] each element of is cumulativeAttendance.append(num2) and num2 is attendance[i] + cumulativeAttendance = [i] I did this like this, but I think there must be a better way. Why reinvent the wheel? attnAdded = [0] for i in range(0, len(studiAttAll)): num1 = studiAttAll[i] #print('num1 is ' + str(num1)) num2 = studiAttAll[i] + attnAdded[i] #print('num2 is ' + str(num2)) attnAdded.append(num2) del attnAdded[0]Is there already a python module to do this? Add the members of a list and write them to a new list such that: newlist[0] = 0 newlist[1] = newlist[0] + oldlist[1] newlist[2] = newlist[1] + oldlist[2] newlist[3] = newlist[2] + oldlist[3] I have strained my tiny brain this afternoon, any tips greatly appreciated! RE: how to add the numbers of a list - Yoriz - Apr-07-2019 def calc_cumulative_attendance(attendance): cumulative_attendance = [attendance[0]] for item in attendance[1:]: cumulative_attendance.append(item + cumulative_attendance[-1]) return cumulative_attendance print(calc_cumulative_attendance([1, 1, 1, 1])) print(calc_cumulative_attendance([0, 1, 0, 1]))
RE: how to add the numbers of a list - perfringo - Apr-07-2019 (Apr-07-2019, 11:19 AM)Pedroski55 Wrote: Is there already a python module to do this? There is built-in module itertools and in there is function accumulate which can be used (in documentation there is also rough code how it is implemented). >>> from itertools import accumulate >>> list(accumulate([1, 1, 1, 1])) [1, 2, 3, 4] >>> list(accumulate([0, 1, 0, 1])) [0, 1, 1, 2] |