简体   繁体   中英

Python - How to check if the next value in a list is the same as the previous?

Let's say we have this array:

arr2 = [2, 3, 1, 2, 2]

I've tried the following:

for i,x in enumerate(arr2):
 
    if x == 2 and x[i+1] == 2:
 
        print('TwosPair')

But receiving the following error:

TypeError: 'int' object is not subscriptable

Shouldn't I be able to check the previous index / next one, using enumerate?

I also tried the following:

for i,x in enumerate(arr2):

    if x == 2 and x[arr2.index(i)+1] == 2:
 
        print('TwosPair')

But getting this error now:

ValueError: 0 is not in list

What 0 is it talking about?

You are a bit unclear, however if you want to check if the previous index has the same value as the next index relative. Zip will allow you iterate over the two lists the frist is the original and the second is sliced to be one element a head since is its frist item is one index ahead the original allowing to access the current and next indexes of the original list

    def TwosPair(list_1):
        for curr, next in zip(list_1, list_1[1:]): 
            if curr == 2 and next == 2: print('TwosPair')


    
arr2 = [2, 3, 3, 1, 2, 2, 9, 4, 4]

for i in range(len(arr2)-1):
    if arr2[i] == arr2[i+1]:
        print('Same next & current values!')

you can use this to find the current and next values when both of them have the same value.

Does this do what you need it to?

arr2 = [2, 3, 1, 2, 2]

for i,x in enumerate(arr2):
    if i < len(arr2)-1 and arr2[i+1] == x:
        print('TwosPair')

This accepts any iterable, including generators and containers such as a list, and reports on whether two adjacent elements are equal.

from typing import Iterable


def has_adjacent_dup(a: Iterable):
    sentinel = object()  # might use None if None won't appear in input
    prev = sentinel
    for i in a:
        if prev == i:
            return True
        prev = i
    return False


if has_adjacent_dup(arr2):
    print('Pair')

You can use zip() :

arr2 = [2, 3, 1, 2, 2]

for x,y in zip(arr2,arr2[1:]):
    if x == y == 2:
        print('TwosPair')

Output:

TwosPair

To answer your specific question, the 0 it is talking about is the 0 value that i takes in the first iteration of the enumerate generator and then when it tries to find that i in the array via arr2.index(i), it throws an error

I believe your approach is basically sound -- we just need to tweak it a little. First, we're going to use the second argument to enumerate() to make its generated value the next index. Second, we're going to limit the array loop to all but the last item so we don't overflow the array indicies. Finally, we'll use some fun Python syntax to simplify the test:

array = [2, 3, 1, 2, 2]

for next_index, element in enumerate(array[:-1], 1):

    if element == 2 == array[next_index]:

        print('TwosPair')

One efficient implementation of this requirement in Python is to use itertools.groupby .

from itertools import groupby

for k, g in groupby(arr):
    if k == 2:
       next(g)
       for _ in g:
           print("TwosPair")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM