在Python中使用[]和list()之间的区别
问题描述:
有人可以解释这段代码吗?
Can somebody explain this code ?
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
对象转换为列表时,它仅采用键.
When you convert a dict
object to a list, it only takes the keys.
但是,如果将其用方括号括起来,它将使所有内容保持不变,只会使它成为dict
的列表,并且其中仅包含一项.
However, if you surround it with square brackets, it keeps everything the same, it just makes it a list of dict
s, with only one item in it.
>>> 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
循环进行循环时,它也只使用了键:
This is because, when you loop over with a for
loop, it only takes the keys as well:
>>> for k in obj:
... print k
...
1
3
5
7
>>>
但是,如果要获取键和,请使用.items()
:
But if you want to get the keys and the values, use .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__
相同:
However, when you type in list.__doc__
, it gives you the same as [].__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
>>>
有点误导:)