gpt4 book ai didi

python - 单个可迭代列表 `list(x)` 与 `[x]` 之间有什么区别?

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:52 24 4
gpt4 key购买 nike

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

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

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

虽然第一个表达式似乎按预期工作,但第二个表达式更像是以这种方式迭代字典:

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

最佳答案

[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 的所有内置集合类型(集合、列表、元组、collections.deque 等)一样 - 可以采用单个可迭代参数并转换它。

关于python - 单个可迭代列表 `list(x)` 与 `[x]` 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50999726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com