我是一个 python 新手,我一直在用 python 解决 Advent of Code 问题。然而,我在解决第2天的问题时遇到了问题。
我定义了一个
dict
将 tuple
映射到一个常量值。具体来说,我将score_table
定义为:
score_table = {('A', 'X'): 3, ('A', 'Y'): 6, ('A', 'Z'): 0,
('B', 'X'): 0, ('B', 'Y'): 3, ('B', 'Z'): 6,
('C', 'X'): 6, ('C', 'Y'): 0, ('C', 'Z'): 3}
但后来,当我尝试通过以下方式访问字典时,我收到了来自 pyright 的错误消息:
for line in f:
u, v = line.split()
ans = ans + score[v] + score_table[(u, v)]
错误说
Argument of type "tuple[str, str]" cannot be assigned to parameter "__key" of type "tuple[Literal['A'], Literal['X']] | tuple[Literal['A'], Literal['Y']] | tuple[Literal['A'], Literal['Z']] | tuple[Literal['B'], Literal['X']] | tuple[Literal['B'], Literal['Y']] | tuple[Literal['B'], Literal['Z']] | tuple[Literal['C'], Literal['X']] | tuple[Literal['C'], Literal['Y']] | tuple[Literal['C'], Literal['Z']]" in function "__getitem__"
Type "tuple[str, str]" cannot be assigned to type "tuple[Literal['A'], Literal['X']] | tuple[Literal['A'], Literal['Y']] | tuple[Literal['A'], Literal['Z']] | tuple[Literal['B'], Literal['X']] | tuple[Literal['B'], Literal['Y']] | tuple[Literal['B'], Literal['Z']] | tuple[Literal['C'], Literal['X']] | tuple[Literal['C'], Literal['Y']] | tuple[Literal['C'], Literal['Z']]"
"tuple[str, str]" is incompatible with "tuple[Literal['A'], Literal['X']]"
Tuple entry 1 is incorrect type
"str" cannot be assigned to type "Literal['A']"
"tuple[str, str]" is incompatible with "tuple[Literal['A'], Literal['Y']]"
Tuple entry 1 is incorrect type
"str" cannot be assigned to type "Literal['A']"
"tuple[str, str]" is incompatible with "tuple[Literal['A'], Literal['Z']]" (reportGeneralTypeIssues)
1 error, 0 warnings, 0 informations
Completed in 0.594sec
然而,我能够运行代码,甚至做对了问题。我做错了什么吗?
供参考,下面是我的整个程序
if __name__ == "__main__":
with open("day2.in", "r", encoding="utf-8") as f:
# A, X = rock, B, Y = paper, C, Z = scissors
score = {'X': 1, 'Y': 2, 'Z': 3}
score_table = {('A', 'X'): 3, ('A', 'Y'): 6, ('A', 'Z'): 0,
('B', 'X'): 0, ('B', 'Y'): 3, ('B', 'Z'): 6,
('C', 'X'): 6, ('C', 'Y'): 0, ('C', 'Z'): 3}
ans = 0
for line in f:
u, v = line.split()
ans = ans + score[v] + score_table[(u, v)]
print(ans)
提前谢谢你!