在Python中,使用[]和list()有什么区别?

13

有人可以解释一下这段代码吗?

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'>

我猜list使用dict.keys(),第一个是字典列表。 - bozdoz
4
dict 是可迭代的(按键),list() 接受一个可迭代对象并返回列表。 - cmd
4个回答

23

当你将一个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
>>> 

有点误导 :)

2
__doc__是类(list)的属性,所以它的实例([])也有这个属性。 - Ashwini Chaudhary

7
  • The former just wraps the entire item in square brackets [], making it a one-item list:

    >>> [{'foo': 1, 'bar': 2}]
    [{'foo': 1, 'bar': 2}]
    
  • The latter iterates over the dictionary (getting keys) and produces a list out of them:

    >>> list({'foo': 1, 'bar': 2})
    ['foo', 'bar']
    

还有一件值得提到的事情:如果你只想在列表中创建一个元素,list() 可能会出现错误,例如 list(3)。只有[3]可以工作。 - Alston

3
>>> help(list)

Help on class list in module __builtin__:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items

在第一种情况下,符号表示您正在创建一个以字典为对象的列表。该列表被创建为空,并将字典作为对象附加到其中。
在第二种情况下,您调用列表构造函数的第二种形式 -“从可迭代的项初始化”。在字典中,可迭代的是键,因此您会得到一个字典键的列表。

3

列表(List)是一个构造函数,可以将任何基本序列(如元组、字典、其他列表等)转换为列表。或者,您可以使用 [] 来创建列表,并在括号内放置所有要添加的内容。您实际上可以通过列表推导式完成相同的操作。

 13 = [item for item in {'from': 55, 'till': 55, 'interest': 15}]
 14 = list({'from': 55, 'till': 55, 'interest': 15})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接