python - 为什么海象运算符不增加我的索引
问题描述
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 指出的那样,索引会提前增加。哎呀...
解决方案
它确实增加了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()
推荐阅读
- java - 专用 Spring Container 与 Spring Scope
- java - MacOS 上的 OpenJDK8 和 JavaFX
- node.js - 如何将 Express Nodejs 中的发布请求对象导出到另一个模块
- python - Pandas groupby concat/merge?转换顺序时间序列
- llvm - 将 i1 类型转换为整数值
- angular - Angular:TypeError:interceptors.reduceRight 不是函数
- django - 使用令牌身份验证获取 Django“self.request.user”
- tensorflow - Anaconda 读取错误的 CUDA 版本
- elasticsearch - 在创建索引时应用索引配置
- mysql - SQL - 替换 HAVING COUNT(*) == 0