Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

python - How to find the longest consecutive non-zero subset of a list?

I have a list of floats that somewhat looks like this:

[
 163.33333333333334,
 0.0,
 0.0,
 154.73684210526315,
 172.94117647058823,
 155.8303886925795,
 0.0,
 156.93950177935943,
 0.0,
 0.0,
 0.0,
 151.5463917525773,
 0.0,
 0.0,
 0.0,
 0.0,
 0.0,
 0.0,
 0.0,
 0.0,
 0.0,
 165.1685393258427,
 156.93950177935943,
 169.6153846153846,
 159.7826086956522,
 167.04545454545453,
 158.06451612903226,
 168.9655172413793,
 157.5,
 0.0,
 159.7826086956522,
 0.0,
 163.94052044609666,
 166.41509433962264,
 0.0,
 0.0,
 0.0,
]

The actual list is much larger than this but has similar values. From this list, I want to find the largest consecutive subset of this that is nonzero. In this case that would be:


 [165.1685393258427,
 156.93950177935943,
 169.6153846153846,
 159.7826086956522,
 167.04545454545453,
 158.06451612903226,
 168.9655172413793]

I am new to python and python and coding in general so any help would be greatly appreciated.

question from:https://stackoverflow.com/questions/65893675/how-to-find-the-longest-consecutive-non-zero-subset-of-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use itertools.groupby, grouping on whether the values are 0 or not, then select all sublists which have non-zero values and find the one with the maximum length:

from itertools import groupby

g = groupby(l, key=lambda x:x>0.0)
m = max([list(s) for v, s in g if v > 0.0], key=len)
print(m)

Output (for your sample data):

[
 165.1685393258427,
 156.93950177935943,
 169.6153846153846,
 159.7826086956522,
 167.04545454545453,
 158.06451612903226,
 168.9655172413793,
 157.5
]

Note that since you only need to compare with 0, you can just use bool as the groupby function (i.e. g = groupby(l, bool)). This should be faster than comparing with 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...