推荐学习书目
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 · Jan 2, 2022 · 3158 views
    This topic created in 1599 days ago, the information mentioned may be changed or developed.

    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 replies    2022-01-03 15:26:01 +08:00
    Osk
        1
    Osk  
       Jan 2, 2022   ❤️ 1
    是的
    还有 typing.Tuple, Dict 等
    lisongeee
        2
    lisongeee  
       Jan 3, 2022   ❤️ 2
    python3.9 可以直接用小写 list[int],不需要 from typing import List
    vcfghtyjc
        3
    vcfghtyjc  
       Jan 3, 2022   ❤️ 1
    是的。另外,删除这些对类型的声明不会影响程序。
    dingwen07
        4
    dingwen07  
       Jan 3, 2022 via iPhone   ❤️ 1
    List[int] 算是 type hint ,python 并没有强制执行类型提示,所以可以直接移除不影响代码执行
    2i2Re2PLMaDnghL
        5
    2i2Re2PLMaDnghL  
       Jan 3, 2022   ❤️ 1
    是的,leetcode 自带一堆 import ,可能可以打印一下 globals() 看看?
    philxjl
        6
    philxjl  
       Jan 3, 2022
    可以考虑用打印一下引入的模块,typing 好像是最后几个
    import sys
    for idx, key in enumerate(sys.modules.keys()):
    print(idx, key)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1029 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 62ms · UTC 19:01 · PVG 03:01 · LAX 12:01 · JFK 15:01
    ♥ Do have faith in what you're doing.