单个可迭代 `list(x)` 与 `[x]` 的列表有什么区别? [英] What is the difference between a list of a single iterable `list(x)` vs `[x]`?
问题描述
Python似乎在 [x]
和 list(x)
之间进行区分,其中 x
是可迭代的.为什么会有这种差异?
>>>a = [dict(a = 1)]>>>[{'a':1}]>>>一个=列表(dict(a = 1))>>>a = ['a']
虽然第一个表达式似乎可以按预期工作,但第二个表达式的工作方式更像是迭代dict:
>>>l = []>>>对于{'a':1}中的e:l.append(e)>>>升>>>['一种']
[x]
是一个包含 element x
的列表./p>
list(x)
接受 x
(必须已经可迭代!)并将其转换为列表.
>>>[1]#列表文字[1]>>>['abc']#包含'abc'的列表['abc']>>>列表(1)#TypeError>>>list((1,))#列表构造函数[1]>>>list('abc')#字符串是可迭代的['a', 'b', 'c'] # 把字符串变成列表!
列表构造函数 list(...)
-像python的所有内置集合类型(集合,列表,元组,collection.deque等)一样-可以采用单个可迭代参数并进行转换.
Python seems to differentiate between [x]
and list(x)
when making a list object, where x
is an iterable. Why this difference?
>>> a = [dict(a = 1)]
>>> [{'a' : 1}]
>>> a = list(dict(a=1))
>>> a = ['a']
While the 1st expression seems to work as expected, the 2nd expression works more like iterating a dict this way:
>>> l = []
>>> for e in {'a' :1}:
l.append(e)
>>> l
>>> ['a']
[x]
is a list containing the element x
.
list(x)
takes x
(which must already be iterable!) and turns it into a list.
>>> [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!
The list constructor list(...)
- like all of python's built-in collection types (set, list, tuple, collections.deque, etc.) - can take a single iterable argument and convert it.
这篇关于单个可迭代 `list(x)` 与 `[x]` 的列表有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!