推荐学习书目
› 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
limyel
V2EX  ›  Python

Python 中 list() 与 [] 有什么区别吗

  •  
  •   limyel · Mar 22, 2020 · 5138 views
    This topic created in 2417 days ago, the information mentioned may be changed or developed.

    最近在模仿 bottle 写一个迷你 web 框架,有一个地方是在构造响应头

    	start_response(status, list(response.header.items()))
    

    其中 response.header.items 是一个生成器,如上述代码中用 list(),生成器就会自动展开,但是用 [] 就只是返回一个包含生成器的列表。

    所以请假一下大家,这两者是有什么区别吗

    14 replies  •  2020-03-24 10:08:19 +08:00
    ahdw
    ahdw
    Mar 22, 2020
    1
    据我的经验,list() 函数是把括号里的东西转换成 list 格式,也可以用来创建 list []
    Trim21
    Trim21
    Mar 22, 2020 via iPhone
    2
    括号就是正常的 list 语法,相当于写了一个[generator,]
    你要是想展开可以用[x for x in generator]
    ahdw
    ahdw
    Mar 22, 2020
    3
    [ ] 是创建一个 list,内容是方括号里面的。

    ( cmd + enter 竟然直接把我写了一半的东西发表了……)
    nnqijiu
    nnqijiu
    Mar 22, 2020
    4
    list()可以把别的对象转成 list 对象
    sagaxu
    sagaxu
    Mar 22, 2020 via Android❤️4
    5
    写框架前先把基本语法看一遍吧...
    imn1
    imn1
    Mar 22, 2020
    6
    list(obj) --> list_object[:] ≈= obj[:]
    [obj] --> list_object[0] == obj

    list("abc") --> ['a', 'b', 'c']
    ["abc"] --> ['abc', ]
    inhzus
    inhzus
    Mar 22, 2020 via Android
    7
    没记错的话 [] 作为函数参数的缺省值会发生出乎意料的事情
    hxse
    hxse
    Mar 22, 2020
    8
    >>> a=(i for i in range(5))
    >>> b=(i for i in range(5))
    >>> list(a)==[*b]
    True
    lithbitren
    lithbitren
    Mar 23, 2020
    9
    方括号里面没加星号吧,加星号没见过出啥问题,除非直接上列表解析式才不用加星号,list(iterator)和[*iterator]没遇到过啥不等价问题,后者还快些,但 dict(kwargs)和{**kwargs}就不太一样,前者可以解析子元素长度为 2 的可迭代对象,后者不行。
    lithbitren
    lithbitren
    Mar 23, 2020
    10
    start_response(status, list(response.header.items())) 写成 start_response(status, [*response.header.items()])估计就没啥问题了。
    limyel
    limyel
    OP
    Mar 23, 2020
    11
    @ahdw
    @Trim21
    @nnqijiu
    感谢解答🙏
    limyel
    limyel
    OP
    Mar 23, 2020
    12
    @sagaxu
    哈哈哈新人想不自量力一下
    limyel
    limyel
    OP
    Mar 23, 2020
    13
    @lithbitren
    我明白了,感谢🙏
    bnm965321
    bnm965321
    Mar 24, 2020
    14
    [] 这是 literal 构造器,字面量构造器
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5417 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 68ms · UTC 03:18 · PVG 11:18 · LAX 19:18 · JFK 22:18
    ♥ Do have faith in what you're doing.