如何打印所有连续负值的总和
How to Print the sum of all the consecutive negative values
我想打印列表中所有连续负值的总和
示例
lst = [1,-1,-3,2,3,4,-5,-1,-3,5,-3,-1,5,4]
我想打印 :
的总和
(-1, -3) ;(-5,-1,-3); (-3,-1)
在列表理解中使用 itertools.groupby
:
lst = [1,-1,-3,2,3,4,-5,-1,-3,5,-3,-1,5,4]
from itertools import groupby
out = [sum(g) for k,g in groupby(lst, lambda x: x<0) if k]
输出:[-4, -9, -4]
def sum_consecutive(values):
accumulator = 0
for value in values:
if value >= 0:
if accumulator != 0:
print(accumulator)
accumulator = 0
else:
accumulator += value
应该可以
我想打印列表中所有连续负值的总和
示例
lst = [1,-1,-3,2,3,4,-5,-1,-3,5,-3,-1,5,4]
我想打印 :
的总和(-1, -3) ;(-5,-1,-3); (-3,-1)
在列表理解中使用 itertools.groupby
:
lst = [1,-1,-3,2,3,4,-5,-1,-3,5,-3,-1,5,4]
from itertools import groupby
out = [sum(g) for k,g in groupby(lst, lambda x: x<0) if k]
输出:[-4, -9, -4]
def sum_consecutive(values):
accumulator = 0
for value in values:
if value >= 0:
if accumulator != 0:
print(accumulator)
accumulator = 0
else:
accumulator += value
应该可以