`Iterable[(int, int)]` 元组在类型提示中是不允许的
`Iterable[(int, int)]` tuple is not allowed in type hints
我有这个非常简单的代码:
from typing import List, Iterable
Position = (int, int)
IntegerMatrix = List[List[int]]
def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:
"""Given an NxM matrix find the positions that contain a zero."""
for row_num, row in enumerate(matrix):
for col_num, element in enumerate(row):
if element == 0:
yield (col_num, row_num)
这是错误:
Traceback (most recent call last):
File "type_m.py", line 6, in <module>
def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:
File "/usr/lib/python3.5/typing.py", line 970, in __getitem__
(len(self.__parameters__), len(params)))
TypeError: Cannot change parameter count from 1 to 2
为什么我不能将 Int 对的可迭代作为 return 类型?
-> Position
和 Iterable[Any]
都有效,只是 Iterable
和 Position
一起无效。
您应该使用 typing.Tuple[int, int]
来声明元组类型 Position
,而不是 (int, int)
。
我有这个非常简单的代码:
from typing import List, Iterable
Position = (int, int)
IntegerMatrix = List[List[int]]
def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:
"""Given an NxM matrix find the positions that contain a zero."""
for row_num, row in enumerate(matrix):
for col_num, element in enumerate(row):
if element == 0:
yield (col_num, row_num)
这是错误:
Traceback (most recent call last):
File "type_m.py", line 6, in <module>
def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:
File "/usr/lib/python3.5/typing.py", line 970, in __getitem__
(len(self.__parameters__), len(params)))
TypeError: Cannot change parameter count from 1 to 2
为什么我不能将 Int 对的可迭代作为 return 类型?
-> Position
和 Iterable[Any]
都有效,只是 Iterable
和 Position
一起无效。
您应该使用 typing.Tuple[int, int]
来声明元组类型 Position
,而不是 (int, int)
。