V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Deteriorator
V2EX  ›  Python

Python3 中的 List[int] 使用的是 typing 模块么?

  •  
  •   Deteriorator · 2022-01-02 23:46:00 +08:00 · 2159 次点击
    这是一个创建于 815 天前的主题,其中的信息可能已经有所发展或是发生改变。

    leetcode 中的 Python3(python3.9.5) 语言在选择的时候会自动生成一部分代码,参数类型中有 List[int] 类型。

    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            pass
    

    但是我在本地 Pycharm 中运行的时候会找不到 List

    NameError: name 'List' is not defined
    

    导入 typing 后就正常了

    from typing import List
    

    leetcode 是在运行代码之前导入了这个模块么? 在提交代码的时候, 代码中并没有 typing 模块相关的信息

    6 条回复    2022-01-03 15:26:01 +08:00
    Osk
        1
    Osk  
       2022-01-02 23:59:00 +08:00   ❤️ 1
    是的
    还有 typing.Tuple, Dict 等
    lisongeee
        2
    lisongeee  
       2022-01-03 02:16:15 +08:00   ❤️ 2
    python3.9 可以直接用小写 list[int],不需要 from typing import List
    vcfghtyjc
        3
    vcfghtyjc  
       2022-01-03 08:32:52 +08:00   ❤️ 1
    是的。另外,删除这些对类型的声明不会影响程序。
    dingwen07
        4
    dingwen07  
       2022-01-03 08:52:39 +08:00 via iPhone   ❤️ 1
    List[int] 算是 type hint ,python 并没有强制执行类型提示,所以可以直接移除不影响代码执行
    2i2Re2PLMaDnghL
        5
    2i2Re2PLMaDnghL  
       2022-01-03 10:14:19 +08:00   ❤️ 1
    是的,leetcode 自带一堆 import ,可能可以打印一下 globals() 看看?
    philxjl
        6
    philxjl  
       2022-01-03 15:26:01 +08:00
    可以考虑用打印一下引入的模块,typing 好像是最后几个
    import sys
    for idx, key in enumerate(sys.modules.keys()):
    print(idx, key)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3775 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:36 · PVG 18:36 · LAX 03:36 · JFK 06:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.