Sum consecutive numbers in a list. Python
问题 i'm trying to sum consecutive numbers in a list while keeping the first one the same. so in this case 5 would stay 5, 10 would be 10 + 5 (15), and 15 would be 15 + 10 + 5 (30) x = [5,10,15] y = [] for value in x: y.append(...) print y [5,15,30] 回答1: y = [sum(x[:i+1]) for i in range(len(x))] 回答2: You want itertools.accumulate() (added in Python 3.2). Nothing extra needed, already implemented for you. In earlier versions of Python where this doesn't exist, you can use the pure python