在Python中使用[]和list()之间的区别

Web*_*ode 10 python list

有人可以解释这段代码吗?

l3 = [ {'from': 55, 'till': 55, 'interest': 15}, ]
l4 = list( {'from': 55, 'till': 55, 'interest': 15}, )

print l3, type(l3)
print l4, type(l4)
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

[{'till': 55, 'from': 55, 'interest': 15}] <type 'list'>
['till', 'from', 'interest'] <type 'list'>
Run Code Online (Sandbox Code Playgroud)

A.J*_*pal 21

dict对象转换为列表时,它只接受键.

但是,如果用方括号括起来,它会保持一切相同,它只是使它成为dicts 的列表,其中只有一个项目.

>>> obj = {1: 2, 3: 4, 5: 6, 7: 8}
>>> list(obj)
[1, 3, 5, 7]
>>> [obj]
[{1: 2, 3: 4, 5: 6, 7: 8}]
>>> 
Run Code Online (Sandbox Code Playgroud)

这是因为,当您使用循环进行for循环时,它也只需要键:

>>> for k in obj:
...     print k
... 
1
3
5
7
>>> 
Run Code Online (Sandbox Code Playgroud)

但是如果你想获得密钥值,请使用.items():

>>> list(obj.items())
[(1, 2), (3, 4), (5, 6), (7, 8)]
>>> 
Run Code Online (Sandbox Code Playgroud)

使用for循环:

>>> for k, v in obj.items():
...     print k, v
... 
1 2
3 4
5 6
7 8
>>> 
Run Code Online (Sandbox Code Playgroud)

但是,当您输入时list.__doc__,它会给您相同的[].__doc__:

>>> print list.__doc__
list() -> new list
list(sequence) -> new list initialized from sequence's items
>>> 
>>> print [].__doc__
list() -> new list
list(sequence) -> new list initialized from sequence's items
>>> 
Run Code Online (Sandbox Code Playgroud)

有点误导:)

  • `__doc__`是class(`list`)属性,难怪它的实例(`[]`)也有. (2认同)

Ale*_*ton 7