我在property
上定义了以下class
:
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
抱怨上面这段代码的最后一行,信号明显:
预期类型为“ List [List [int]]”,而不是“ List [Iterable]” ...
这很令人惊讶,因为:
indices
被声明为list
ravel
确保将argwhere
的匹配值转换为一维Numpy
向量tolist
将一维Numpy
矢量转换为列表indices
列表中由于在IDE端对类型提示的处理不正确,这可能是误报,因为List[int]
实际上是Iterable
...,因此也是List[List[int]] = List[Iterable]
。但是我不能百分百确定。
有关此问题的任何线索吗?如何确保将返回值强制为期望的类型?
答案 0 :(得分:0)
感谢@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]))