简体   繁体   中英

Python - Printing duplicates after getting previous and next element in a list

Sorry for the beginner question -- In running this code, it prints the output twice rather than printing once and then continuing on to the next iteration of the loop. I'm sure this is simply a formatting error, but I can't seem to spot it... Thanks!

myList = [1, 1, 1, 0.5, 1, 1, 2, 1, 0.5, 1, 3]

for thisThing in myList: 
    baseIndex = myList.index(thisThing)

    if thisThing == 0.5:
        get_previous = myList[baseIndex - 1]
        get_next = myList[baseIndex + 1]

        T2 = thisThing * 2
        if T2 == get_previous and T2 == get_next:
            print("Success at index " + str(myList.index(thisThing)))
            continue

OUTPUT:
Success at index 3
Success at index 3

index returns the index of first occurrence of the given item, in this case 3 . You could fix the code by changing it to iterate index instead:

myList = [1, 1, 1, 0.5, 1, 1, 2, 1, 0.5, 1, 3]

for baseIndex in range(1, len(myList) - 1):
    thisThing = myList[baseIndex]

    if thisThing == 0.5:
        get_previous = myList[baseIndex - 1]
        get_next = myList[baseIndex + 1]

        T2 = thisThing * 2
        if T2 == get_previous and T2 == get_next:
            print("Success at index " + str(baseIndex))

Output:

Success at index 3
Success at index 8

Since the above will only iterate the indexes 1 - 8 it will also work in case that 0.5 is the first or last element.

You could also use enumerate and zip to iterate over tuples (prev, current, next) :

for i, (prev, cur, nxt) in enumerate(zip(myList, myList[1:], myList[2:]), 1):
    t2 = cur * 2
    if cur == 0.5 and prev == t2 and nxt == t2:
        print("Success at index " + str(i))

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