Ari*_*her 7 python python-3.x python-typing
我真的不确定为什么这行不通。这是代码的重要部分(来自leetcode挑战)。第一行抛出NameError。
def totalFruit(self, tree: List[int]) -> int:
pass
Run Code Online (Sandbox Code Playgroud)
如果我尝试List
先导入,则会出现错误No module named 'List'
。我正在使用Anaconda的Python 3.7.3。
Ada*_*Er8 32
从Python 3.9 开始,您可以使用内置集合类型(例如list
)作为泛型类型,而不是从typing
.
这要归功于PEP 585
因此,在 Python 3.9 或更高版本中,您实际上可以编写:
def totalFruit(self, tree: list[int]) -> int: # Note list instead of List
pass
Run Code Online (Sandbox Code Playgroud)
无需导入任何东西。
Lau*_*Mat 12
为了能够注释列表应接受的类型,您需要使用 typing.List
from typing import List
Run Code Online (Sandbox Code Playgroud)
那你进口了List
吗?