I want to know how to find if there is a certain amount of consecutive numbers in a row in my list e.g.
For example if I am looking for two 1's then:
list = [1, 1, 1, 4, 6] #original list
list = ["true", "true", 1, 4, 6] #after my function has been through the list.
If I am looking for three 1's then:
list = [1, 1, 1, 4, 6] #original list
list = ["true", "true", "true", 4, 6] #after my function has been through the list.
I have tried:
list = [1, 1, 2, 1]
1,1,1 in list #typed into shell, returns "(1, 1, True)"
Any help would be greatly appreciated, I mainly would like to understand whats going on, and how to check if the next element in the list is the same as the first x amount.
It is a bad idea to assign to list
. Use a different name.
To find the largest number of consecutive equal values you can use itertools.groupby
>>> import itertools
>>> l = [1, 1, 1, 4, 6]
>>> max(len(list(v)) for g,v in itertools.groupby(l))
3
To search only for consecutive 1s:
>>> max(len(list(v)) for g,v in itertools.groupby(l, lambda x: x == 1) if g)
3
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