Derive Sub List From A Long List Depending In Value
I have a list like below, list = [0,0,0,0,2,1,4,1,432,431,1,4,43,423,,45,54534,0,665,765,5687,89870,890,98089,6,0,1,5,7,3,6,7,8,3,4,4,7,543,6554,765,768,87234,765876,0,897,987,0,4,
Solution 1:
lists= []
low=Truefor n in main_list:ifn>10:if not low:lists[-1].append(n)else:lists.append([n])low=Falseelse:low=TrueSolution 2:
Here's some working code, supposedly commented heavily enough.
sample = [0,0,0,0,2,1,4,1,
432,431,1,4,43,423,45,54534,0,665,765,5687,89870,890,98089,
6,0,1,5,7,3,6,7,8,3,4,4,7,
543,6554,765,768,87234,765876,0,897,987,
0,4,7,4,6,8,0,0,0,0]
deffindStreak(data, initial_index, threshold=10, allowed_fluctuation_length=2):
"""Looks for a streak with values all below or all above threshold.
* data: the list to scan.
* initial_index: where to start looking.
* thresold: a value that determines the upper/lower limit of the streak.
* allowed_fluctuation_length: how many values may be beyond threshold
without breaking the streak.
Returns a tuple (start, end), so that data[start : end] is the streak,
or None if initial_index is out of range.
"""if0 <= initial_index < len(data):
# determine what kind of streak we want to seeif data[initial_index] > threshold:
belongsToStreak = lambda x: x > threshold # high streakelse:
belongsToStreak = lambda x: x <= threshold # low streak# scan forward as long as predicate holds
last_good_index = initial_index # where the streak still has not ended
index = initial_index + 1
fluctuation_length = 0# how many values did not satisfy the predicatewhile index < len(data):
ifnot belongsToStreak(data[index]):
fluctuation_length += 1if fluctuation_length > allowed_fluctuation_length:
# it was not a fluctuation, it's another streak beginning!return (initial_index, last_good_index + 1)
else:
last_good_index = index # position under index belongs to the streak
index += 1# advance# we ran out of data, but the streak did not seem to endreturn (initial_index, last_good_index + 1)
# here initial_index is out of range# we could omit this; if a function does not return something explicitly,# it implicitly returns None.returnNonedefprintStreaks(data=sample):
initial_index = 0whileTrue:
streak_span = findStreak(data, initial_index)
ifnot streak_span:
break
initial_index, end_index = streak_span # unpack the tupleprint"Streak is %r, data is %r" % (
streak_span,
data[initial_index : end_index])
initial_index = end_index # advance to next streakNow try printStreaks(sample), also try with other lists or thresholds.
Note that your first list contains an extra comma that breaks parsing.
Post a Comment for "Derive Sub List From A Long List Depending In Value"