有人可以解释这段代码吗?
l3 = [ {'from': 55, 'till': 55, 'interest': 15}, ]
l4 = list( {'from': 55, 'till': 55, 'interest': 15}, )
print l3, type(l3)
print l4, type(l4)
输出:
[{'till': 55, 'from': 55, 'interest': 15}] <type 'list'>
['till', 'from', 'interest'] <type 'list'>
最佳答案
当您将 dict
对象转换为列表时,它只需要键。
但是,如果你用方括号括起来,它会保持一切不变,它只是使它成为一个 dict
的列表,其中只有一个项目。
>>> obj = {1: 2, 3: 4, 5: 6, 7: 8}
>>> list(obj)
[1, 3, 5, 7]
>>> [obj]
[{1: 2, 3: 4, 5: 6, 7: 8}]
>>>
这是因为,当您使用 for
循环进行循环时,它也只接受键:
>>> for k in obj:
... print k
...
1
3
5
7
>>>
但是如果你想得到键和值,使用.items()
:
>>> list(obj.items())
[(1, 2), (3, 4), (5, 6), (7, 8)]
>>>
使用 for
循环:
>>> for k, v in obj.items():
... print k, v
...
1 2
3 4
5 6
7 8
>>>
但是,当您输入 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
>>>
有点误导:)
关于python - 在 Python 中使用 [] 和 list() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23703109/