我试图在python中按值列出一个列表,我没有运气。我最终想要的是三个求和值。
lst = [100, -1, -2, -3, 100, -1, -2, -3, 100]
100 -1-2-3 = 94
100 -1-2-3 = 94
100 = 100
答案 0 :(得分:2)
这个怎么样?
s = []
for i in lst:
if i > 0 or len(s) == 0:
s.append(i) # start a new element in s when element is larger than zero
else:
s[-1] += i # otherwise add it to the last element of s
s
# [94, 94, 100]
或者如果您使用pandas:
import pandas as pd:
ser = pd.Series(lst)
ser.groupby((ser > 0).cumsum()).sum()
#1 94
#2 94
#3 100
#dtype: int64