繁体   English   中英

在列表中查找连续的负值

[英]Finding consecutive negative values in list

例如,我有这个列表,我想找到连续的负值和总计并将总计附加到列表 b 然后在列表 b 中找到最小值,我尝试了很多解决方案但没有奏效。

a= [4, -3, -2, 2, 3, 5, 6, 4, 2, -5, -4, -3, 3, 7, -2, 4, -2, 9]
b= []

[-3, -2] = -5
[-5, -4, -3] = -12

b= [-5, -12]

我想得到这个答案:-12

我确实尝试过谷歌的这段代码

a= [4,-3,-2,2,3,5,6,4,2,-5,-4,-3,3,45,-2,4,-2,5]
def consecutive_counts(arr):
    
    #  Returns number of consecutive negative and positive numbers
    # arr = np.array
    # negative = consecutive_counts(a)[0]
    # positive = consecutive_counts(a)[1]
    
    pos = arr > 0
    # is used to Compute indices that are non-zero in the flattened version of arr
    idx = np.flatnonzero(pos[1:] != pos[:-1])
    count = np.concatenate(([idx[0]+1], idx[1:] - idx[:-1], [arr.size-1-idx[-1]]))
    negative = count[1::2], count[::2]
    positive = count[::2], count[1::2]
    if arr[0] < 0:
        return negative
        
    else:
        return positive

这是一种方法:

from itertools import groupby

a= [4, -3, -2, 2, 3, 5, 6, 4, 2, -5, -4, -3, 3, 7, -2, 4, -2, 9]

for g,k in groupby(a, key =lambda x: x<0):
    vals = list(k)
    if g== True and len(vals) > 1:
        print(sum(vals))

注意-> 这是一行版本 -

result = [sum(k) for g, k in ((i,list(j)) for i,j in (groupby(a, key=lambda x: x < 0))) if g == True and len(k) > 1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM