【问题标题】:NameError: name 'List' is not definedNameError:名称“列表”未定义
【发布时间】:2019-08-15 05:06:10
【问题描述】:

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

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

如果我首先尝试导入 List,我会收到错误 No module named 'List'。我正在使用 Anaconda 的 Python 3.7.3。

【问题讨论】:

    标签: python python-3.x python-typing


    【解决方案1】:

    为了能够注释您的列表应接受的类型,您需要使用typing.List

    from typing import List
    

    那么你导入List了吗?

    更新

    如果您使用 Python > 3.9,see @Adam.Er8's answer

    【讨论】:

    • 顺便说一下,这段代码会有更多问题。 for i, t in tree 将在您尝试将整数解压缩为两个值时产生 TypeError。
    • 太棒了 from typing import List 似乎可以解决问题,还必须修复我的代码中其他不相关的错误,非常感谢!
    【解决方案2】:

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

    所以在 Python 3.9 或更高版本中,您实际上可以编写:

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

    无需导入任何东西。

    【讨论】:

    • 让我说,是的!:)
    • 使其向后兼容:from __future__ import annotations(来自文档)
    • 这对def totalFruit() -> list[int]: 也有效吗?还是只对参数有效?
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      如果我们定义了a = [1,2,3]这样的列表,那么type(a)会返回<class 'list'>,也就是说它会被内置的list创建。

      List 对于注释返回类型很有用。例如,使用 Python3 的函数签名:def threeSumClosest(self, nums: List[int], target: int) -> int: from https://leetcode.com/problems/integer-to-roman/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        • 2021-04-15
        • 2019-01-26
        • 2021-10-05
        • 2017-08-16
        • 2019-08-18
        相关资源
        最近更新 更多