-1
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 指出的那样,索引会提前增加。哎呀...

4

2 回答 2

2

它确实增加了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()
于 2020-02-07T15:19:00.537 回答
0

您在循环index开始时重置为 -1 。for确实第一次成功递增(打印了 100,而不是 103,如果它没有的话,你会期望它 - 显然,打印语句是用index == 0, not执行的index == -1,这可能只是因为第一次打印中的赋值运算符声明),但你下次重置它。所以,增加一次是 100,再增加一次是 101,等等。

删除该分配,并将其保留在 for 循环之外IndexError,随着索引攀升至高于 3,您将得到您所期望的。

于 2020-02-07T15:19:25.017 回答