首页 > 解决方案 > 为什么海象运算符不增加我的索引

问题描述

aTuple = (100, 101, 102, 103)

for aBool in (False, True):
    index = -1

    if aBool:
        print (aTuple [(index := index + 1)])
        print (aTuple [(index := index + 1)])

    print (aTuple [(index := index + 1)])
    print (aTuple [index])
    print ()

'''
Expected output:

100
101

100
101
102
102


True output:

100
100

100
101
102
102
'''

来自 C++,我期望后增量。但正如@chepner 指出的那样,索引会提前增加。哎呀...

标签: python

解决方案


它确实增加了index;但表达式的值是index

print(aTuple[(index:=index + 1)])具有相同的效果

index = index + 1
print(aTuple[index])

所以在循环结束时,两个print函数看到相同的参数。

--

作为避免显式索引操作的示例,您可以使用具有动态选择起点的切片:

aTuple = (100, 101, 102, 103)

for aBool in (False, True):
    for x in aTuple[:3 if aBool else 1]:
        print(x)
    print()

推荐阅读