在Python中使用[]和list()之间的区别 [英] Difference between using [] and list() in Python

查看:152
本文介绍了在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 dicts, 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
>>> 

有点误导:)

这篇关于在Python中使用[]和list()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆