我在class
上定义了以下property
:
import numpy as np
import typing as tp
@property
def my_property(self) -> tp.List[tp.List[int]]:
if not self.can_implement_my_property:
return list()
# calculations to produce the vector v...
indices = list()
for u in np.unique(v):
indices.append(np.ravel(np.argwhere(v == u)).tolist())
return sorted(indices, key=lambda x: (-len(x), x[0]))
PyCharm
抱怨上面代码段的最后一行,信号:
预期类型为"列表[列表[int]],改为"列表[可迭代]"...
这是非常令人惊讶的,因为:
-
indices
声明为list
-
ravel
确保将argwhere
的匹配值转换为一维Numpy
向量 -
tolist
将一维Numpy
向量转换为列表 - 获得的列表将追加到
indices
列表中
由于 IDE 端对类型提示的错误处理,这可能是误报,因为List[int]
实际上是一个Iterable
......因此List[List[int]] = List[Iterable]
.但我不能100%确定。
关于这个问题有什么线索吗?如何确保将返回值强制转换为预期类型?
感谢@mgilson评论,这是我为解决问题而实施的解决方案:
indices = list()
for u in np.unique(v):
indices.append(list(it.chain.from_iterable(np.argwhere(v == u))))
return sorted(indices, key=lambda x: (-len(x), x[0]))