Python似乎区分[x]和list(x)创建列表对象时,哪里x是可迭代的.为何如此区别?
>>> a = [dict(a = 1)]
>>> [{'a' : 1}]
>>> a = list(dict(a=1))
>>> a = ['a']
Run Code Online (Sandbox Code Playgroud)
虽然第一个表达式似乎按预期工作,但第二个表达式更像是以这种方式迭代一个字典:
>>> l = []
>>> for e in {'a' :1}:
l.append(e)
>>> l
>>> ['a']
Run Code Online (Sandbox Code Playgroud)
[x]是包含该元素 的列表x.
list(x)take 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!
Run Code Online (Sandbox Code Playgroud)
列表构造函数list(...)- 与所有python的内置集合类型(set,list,tuple,collections.deque等)一样 - 可以采用单个可迭代参数并进行转换.