在Python中零之间的列表的总和 [英] Sum elements of a list between zeros in Python

查看:71
本文介绍了在Python中零之间的列表的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

lst = [1, 2, 3, 5, 0, 0, 9, 45, 3, 0, 1, 7]

我需要新列表中0之间的元素总和. 我尝试过

And I need the sum of the elements between the 0s in a new list. 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

,但它返回[11, 0, 0, 0, 57, 0],但我希望 [11, 0, 0, 57, 0, 8]

but it returns [11, 0, 0, 0, 57, 0], while I expect [11, 0, 0, 57, 0, 8]

推荐答案

这是使用 itertools.groupby 列表理解.通过检查元素是否为零来完成分组,如果不为零,则对组中的所有项目求和:

Here's one way to this with itertools.groupby and a list comprehension. 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]

当然,如果列表中的项目仅是数字(为避免泛化和引入歧义),则可以将lambda替换为bool:

And of course, if items in your list are only numbers (to avoid generalising and introducing ambuigities), the lambda can be replaced with bool:

result = [i for k, g in groupby(lst, bool) for i in ((sum(g),) if k else g)]

这篇关于在Python中零之间的列表的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆