python - 在 Python 中使用 [] 和 list() 的区别

标签 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)

输出:

[{'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/

相关文章:

找不到索引时,Python list.index 抛出异常

python - 存储文件信息

python - 用元组替换程序中的列表?

c++ - 我的 List<T> 实现有什么问题?

list - 如何连接两个 Snoc 列表?

PHP:防止项目被多次显示

python - 如何用python查找字符串中多个子字符串的索引?

Python 在可用时逐行读取网站数据

python - 循环比较字符串列表元素与字符串列表子元素的有效方法

python - python列表中最长的连续重复序列