[英]Sum elements of a list between zeros in Python
I have a list: 我有一个清单:
lst = [1, 2, 3, 5, 0, 0, 9, 45, 3, 0, 1, 7]
And I need the sum of the elements between the 0
s in a new list. 我需要新列表中
0
之间的元素总和。 I tried 我试过了
lst1 = []
summ = 0
for i, elem in enumerate(lst):
if elem != 0:
summ = summ + elem
else:
lst1.append(summ)
lst1.append(elem)
summ = 0
but it returns [11, 0, 0, 0, 57, 0]
, while I expect [11, 0, 0, 57, 0, 8]
但它返回
[11, 0, 0, 0, 57, 0]
,而我期望[11, 0, 0, 57, 0, 8]
Here's one way to this with itertools.groupby
and a list comprehension . 这是使用
itertools.groupby
和列表理解的一种方法。 The grouping is done by checking if an element is zero, and if not zero, all items in the group are summed: 通过检查元素是否为零来完成分组,如果不为零,则对组中的所有项进行求和:
from itertools import groupby
lst = [1, 2, 3, 5, 0, 0, 9, 45, 3, 0, 1, 7]
f = lambda x: x==0
result = [i for k, g in groupby(lst, f) for i in (g if k else (sum(g),))]
print(result)
# [11, 0, 0, 57, 0, 8]
And of course, if items in your list are only numbers (to avoid generalising and introducing ambuigities), the lambda
can be replaced with bool
: 当然,如果列表中的项目只是数字(为了避免泛化和引入ambuigities),
lambda
可以用bool
替换:
result = [i for k, g in groupby(lst, bool) for i in ((sum(g),) if k else g)]
you are appending extra summ when its 0, and missing 1 summ at the end 你在0时附加额外的summ,在结尾时丢失1个summ
lst = [1, 2, 3, 5, 0, 0, 9, 45, 3, 0, 1, 7]
lst1 = []
summ = 0
for i, elem in enumerate(lst):
if elem != 0:
summ = summ + elem
else:
if summ:
lst1.append(summ)
lst1.append(elem)
summ = 0
if summ:
lst1.append(summ)
# lst1 = [11, 0, 0, 57, 0, 8]
Just add an extra lst1.append(summ)
after the loop 只需在循环后添加一个额外的
lst1.append(summ)
lst1 = []
summ = 0
for i, elem in enumerate(lst):
if elem != 0:
summ = summ + elem
else:
if summ:
lst1.append(summ)
lst1.append(elem)
summ = 0
lst1.append(summ)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.