列表/数组表示[]和{}之间有什么区别?

时间:2013-03-08 14:13:24

标签: python python-2.7 python-3.x

有什么区别:

dictionary = []

dictionary = {}

假设字典有字符串内容?

2 个答案:

答案 0 :(得分:9)

在第一种情况下,您正在制作list,而另一种情况则是dictlist个对象为sequences,而dict个对象为mappings。请查看python types页面。

基本上,列出“映射”顺序整数(从0开始)到某个对象。这样,它们在其他语言中的行为更像是动态数组。事实上,Cpython将它们实现为C中的过度分配数组。

dict映射对象的哈希键。它们是使用哈希表实现的。


另请注意,从python2.7开始,您可以使用{}创建集合,这是另一种(基本)类型。修改:

[] #empty list
{} #empty dict
set() #empty set

[1] #list with one element
{'foo':1} #dict with 1 element
{1} #set with 1 element

[1, 2] #list with 2 elements
{'foo':1, 'bar':2} #dict with 2 elements
{1, 2} #set with 2 elements. 

答案 1 :(得分:0)

在python 2.x上

>>> type([])
<type 'list'>
>>> type({})
<type 'dict'>
>>>

在python 3.x上

>>> type([])
<class 'list'>
>>> type({})
<class 'dict'>
>>>