【问题标题】:What is the difference between a list of a single iterable `list(x)` vs `[x]`?单个可迭代 `list(x)` 与 `[x]` 的列表有什么区别?
【发布时间】:2021-10-15 13:14:41
【问题描述】:

在创建列表对象时,Python 似乎区分了[x]list(x),其中x 是一个可迭代对象。为什么会有这种差异?

>>> a = [dict(a=1)]
>>> a
[{'a': 1}]

>>> a = list(dict(a=1))
>>> a
['a']

虽然第一个表达式似乎按预期工作,但第二个表达式更像是这样迭代 dict:

>>> l = []
>>> for e in {'a': 1}:
...     l.append(e)
>>> l
['a']

【问题讨论】:

  • [] == list() 可能会给您一种印象,list() 就像例如array() 在 PHP 中——只是一种替代语法——但事实并非如此。它是一种在不带参数调用时给出一个空列表的类型,在使用一个参数调用时将一个可迭代对象转换为一个列表,并且不能使用多个参数调用。 [x] 不等于 list(x)list(x, y, …) 没有意义。

标签: python list


【解决方案1】:

[x] 是一个包含 元素 x 的列表。

list(x) 接受x(必须已经是可迭代!)并将其转换为列表。

>>> [1]  # list literal
[1]
>>> ['abc']  # list containing 'abc'
['abc']
>>> list(1)
# TypeError
>>> list((1,))  # list constructor
[1]
>>> list('abc')  # strings are iterables
['a', 'b', 'c']  # turns string into list!

列表构造函数list(...) - 与所有 python 的内置集合类型(set、list、tuple、collections.deque 等)一样 - 可以采用单个可迭代参数并对其进行转换。

【讨论】:

    猜你喜欢
    • 2010-09-18
    • 1970-01-01
    • 2021-06-07
    • 2014-11-15
    • 1970-01-01
    • 2017-11-15
    • 2015-08-24
    • 2011-05-10
    相关资源
    最近更新 更多