简体   繁体   English

使用 itertools.groupby 返回最长的连续负数列表

[英]Return the longest list of consecutive negative numbers using itertools.groupby

Given the series:鉴于系列:

series = [2, 6, 9, -1, 1, -3, -3, -3, 1,-4]

How do you return the list [-3, -3, -3] using itertools.groupby ?如何使用itertools.groupby返回列表[-3, -3, -3]

Trying:试:

from itertools import groupby
max((list(g) for k, g in groupby(series, key=lambda i: i < 0)), key=len)

returns:返回:

[2, 6, 9]

Thanks in advance提前致谢

You could do:你可以这样做:

from itertools import groupby

series = [2, 6, 9, -1, 1, -3, -3, -3, 1, -4]
result = max((list(group) for key, group in groupby(series) if key < 0), key=len)

print(result)

Output Output

[-3, -3, -3]

The problem with your code is that you are using the wrong key in the groupby, key=lambda i: i < 0 , just filter the results if the key is positive.您的代码的问题是您在 groupby 中使用了错误的键key=lambda i: i < 0 ,如果键为正,只需过滤结果。

Check you k value for True or False.检查你的k值是真还是假。

from itertools import groupby
series = [2, 6, 9, -1, 1, -3, -3, -3, 1,-4]
x = max([list(g) for k, g in groupby(series, key=lambda i: i < 0) if k == True ], key=len)
print(x)

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

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