Python代码:
t = (1,2,3)
t = tuple(x+1 for x in t)
qazxsw ppi投诉:
mypy
我该怎么做才能避免这个错误?这没有帮助:
2: error: Incompatible types in assignment (expression has type "Tuple[int, ...]", variable has type "Tuple[int, int, int]")
这“有效”:
t = (1,2,3)
t = tuple(x+1 for x in t)[0:3]
但实际上我不希望from typing import Tuple
t: Tuple[int, ...] = (1,2,3)
t = tuple(x+1 for x in t)
成为一个可变长度的元组。
我当然可以告诉mypy忽略这一行:
t
或者重复一遍:
t = (1,2,3)
t = tuple(x+1 for x in t) # type: ignore
或者使用临时变量来至少避免重复t = (1,2,3)
t = (t[0]+1, t[1]+1, t[2]+1)
部分(这在现实世界问题中更复杂):
+1
有更好的解决方案吗?
你可以使用t = (1,2,3)
tmp = tuple(x+1 for x in t)
t = (tmp[0], tmp[1], tmp[2])
解决这个问题。
cast