Identify if list has consecutive elements that are equal in python

前端 未结 6 1570
情深已故
情深已故 2020-11-28 15:01

I\'m trying to identify if a large given list has consecutive elements that are the same.

So let\'s say

lst = [1, 2, 3, 4, 5, 5, 6]

6条回答
  •  -上瘾入骨i
    2020-11-28 15:28

    Here a more general numpy one-liner:

    number = 7
    n_consecutive = 3
    arr = np.array([3, 3, 6, 5, 8, 7, 7, 7, 4, 5])
    #                              ^  ^  ^ 
     
    np.any(np.convolve(arr == number, v=np.ones(n_consecutive), mode='valid') 
           == n_consecutive)[0]
    

    This method always searches the whole array, while the approach from @Kasramvd ends when the condition is first met. So which method is faster dependents on how sparse those cases of consecutive numbers are. If you are interested in the positions of the consecutive numbers, and have to look at all elements of the array this approach should be faster (for larger arrays (or/and longer sequences)).

    idx = np.nonzero(np.convolve(arr==number, v=np.ones(n_consecutive), mode='valid') 
                                 == n_consecutive)
    # idx = i: all(arr[i:i+n_consecutive] == number)
    

    If you are not interested in a specific value but at all consecutive numbers in general a slight variation of @jmetz's answer:

    np.any(np.convolve(np.diff(arr), v=np.ones(n_consecutive-1), mode='valid') == 0)
    

提交回复
热议问题