I want to scan a large list for consecutive values that are greater than x. This example x is greater than 1.0.
For example,
my_list = [0.2, 0.1, 0.3, 1.1, 0.7, 0.5, 1.2, 1.3, 1.4, 1.2, 1.9, 1.1, 0.2, 1.3, 1.5, 1.4, 1.2, 1.1, 0.2, 1.3, 0.1., 1.6, 0.2, 0.5, 1.0, 1.1, 0.2]
I can subset this list by
for i in range(0, len(my_list)):
subset = my_list[i:i+5]
so I get
[0.2, 0.1, 0.3, 1.1, 0.7]
[0.1, 0.3, 1.1, 0.7, 0.5]
[0.3, 1.1, 0.7, 0.5, 1.2]
[1.1, 0.7, 0.5, 1.2, 1.3]
[0.7, 0.5, 1.2, 1.3, 1.4]
[0.5, 1.2, 1.3, 1.4, 1.2]
[1.2, 1.3, 1.4, 1.2, 1.9] <-- values I want
[1.3, 1.4, 1.2, 1.9, 1.1] <-- values I want
[1.4, 1.2, 1.9, 1.1, 0.2]
[1.2, 1.9, 1.1, 0.2, 1.3]
[1.9, 1.1, 0.2, 1.3, 1.5]
[1.1, 0.2, 1.3, 1.5, 1.4]
[0.2, 1.3, 1.5, 1.4, 1.2]
[1.3, 1.5, 1.4, 1.2, 1.1] <-- values I want
What is the best way to do this?
If we denote the 1st number as n, then the consecutive numbers in the series will be n, n+1, n+2, n+3, n+4, and so on. For any two consecutive odd numbers, the difference is 2. For example, 3 and 5 are two consecutive odd numbers, their difference = 5 - 3 = 2. For any two consecutive even numbers, the difference is 2.
Here's an itertools
based approach that won't need any extra memory and returns results as a generator:
from itertools import tee, islice
def find_consecutive(the_list, threshold, count=5):
my_iters = tee(the_list, count)
for i, it in enumerate(my_iters):
next(islice(it, i, i), None)
return (f for f in zip(*my_iters) if all(x > threshold for x in f))
my_list = [0.2, 0.1, 0.3, 1.1, 0.7, 0.5, 1.2, 1.3, 1.4, 1.2, 1.9, 1.1, 0.2, 1.3, 1.5, 1.4, 1.2, 1.1, 0.2, 1.3, 0.1, 1.6, 0.2, 0.5, 1.0, 1.1, 0.2]
list(find_consecutive(my_list, 1.0))
# [(1.2, 1.3, 1.4, 1.2, 1.9),
# (1.3, 1.4, 1.2, 1.9, 1.1),
# (1.3, 1.5, 1.4, 1.2, 1.1)]
The function is parameterized by threshold and count so you can look for any N consecutive values. You could even factor out the condition by passing in a function for that instead of just a threshold value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With