名称错误:名称“List”未定义。

114

我真的不确定为什么这不起作用。这是代码的重要部分(它来自于leetcode挑战)。 第一行抛出了NameError。

def totalFruit(self, tree: List[int]) -> int:
    pass

如果先尝试导入List,我会得到一个错误No module named 'List'。 我正在使用来自Anaconda的Python 3.7.3。

4个回答

219
为了能够注释您的列表应该接受哪些类型,您需要使用typing.List
from typing import List

那么,你导入了 List 吗?

更新

如果你使用的是 Python > 3.9,参见 @Adam.Er8 的答案


2
顺便提一下,这段代码会有更多问题。for i, t in tree 会产生 TypeError 错误,因为你试图将一个整数解包成两个值。 - Mathieu Dhondt
太棒了,from typing import List 似乎解决了问题,我还得修复代码中的其他无关错误,非常感谢! - Ariel Frischer

70

自从Python 3.9版本以后,你可以使用内置的集合类型(例如list)作为泛型类型,而不是从typing导入相应的大写类型。
这要感谢PEP 585

因此,在Python 3.9或更新版本中,你实际上可以这样编写:

def totalFruit(self, tree: list[int]) -> int: # Note list instead of List
    pass

不需要导入任何东西。

2
让我说,是的!:) - ntg
3
为了实现向后兼容性:从文档中使用 from __future__ import annotations - Stanislav
这对于 def totalFruit() -> list[int]: 也适用吗?还是只适用于参数? - Kiteration

12
为了能够在类型提示中指定字符串列表,您可以使用 typing 包,并使用 from typing import List(大写,不要与内置的 list 混淆)。

2
如果我们定义一个列表,例如a = [1,2,3],那么type(a)将返回<class 'list'>,这意味着它将被内置的list创建。 List对于注释返回类型非常有用。例如,使用Python3的函数签名:def threeSumClosest(self, nums: List[int], target: int) -> int:来自https://leetcode.com/problems/integer-to-roman/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接