Python - 在列表中获取上一个和下一个元素后打印重复项

时间:2016-11-27 03:03:14

标签: python

抱歉初学者问题 - 在运行此代码时,它会打印输出两次而不是打印一次,然后继续循环的下一次迭代。我确定这只是一个格式错误,但我似乎无法发现它......谢谢!

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

1 个答案:

答案 0 :(得分:1)

index返回给定项的第一次出现的索引,在本例中为3。您可以通过将代码更改为迭代索引来修复代码:

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))

输出:

Success at index 3
Success at index 8

由于上述内容只会迭代索引1 - 8,因此如果0.5是第一个或最后一个元素,它也会起作用。

您还可以使用enumeratezip来迭代元组(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))