有人可以解释这段代码吗?
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)
有点误导:)
前者只是将整个项目包装在方括号中[],使其成为单项列表:
>>> [{'foo': 1, 'bar': 2}]
[{'foo': 1, 'bar': 2}]
Run Code Online (Sandbox Code Playgroud)后者遍历字典(获取密钥)并从中生成一个列表:
>>> list({'foo': 1, 'bar': 2})
['foo', 'bar']
Run Code Online (Sandbox Code Playgroud)