将列表中的连续数字求和.Python [英] Sum consecutive numbers in a list. Python
问题描述
我正在尝试对列表中的连续数字求和,同时保持第一个数字相同.
i'm trying to sum consecutive numbers in a list while keeping the first one the same.
因此在这种情况下5将保持为5,10将为10 + 5(15),而15将为15 + 10 + 5(30)
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]
推荐答案
You want itertools.accumulate()
(added in Python 3.2). Nothing extra needed, already implemented for you.
在不存在此功能的早期Python版本中,您可以使用给定的纯python实现:
In earlier versions of Python where this doesn't exist, you can use the pure python implementation given:
def accumulate(iterable, func=operator.add):
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
total = next(it)
yield total
for element in it:
total = func(total, element)
yield total
这将与任何可迭代的,懒惰的和有效的完美配合. itertools
实现在较低的级别上实现,因此甚至更快.
This will work perfectly with any iterable, lazily and efficiently. The itertools
implementation is implemented at a lower level, and therefore even faster.
如果您希望将其作为列表,那么自然只需使用内置的 list()
: list(accumulate(x))
.
If you want it as a list, then naturally just use the list()
built-in: list(accumulate(x))
.
这篇关于将列表中的连续数字求和.Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!