简体   繁体   English

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

[英]What is the difference between list / array representation [] and {}?

What is the difference between : 之间有什么区别:

dictionary = []

and

dictionary = {}

assuming dictionary has string contents ? 假设字典中有字符串内容?

In the first case, you're making a list whereas the other you're making a dict . 在第一种情况下,您在创建list而在另一种情况下,您在做dict list objects are sequences whereas dict objects are mappings . list对象是序列,dict对象是映射 Have a look at the python types page. 看看python types页面。

Basically, lists "map" sequential integers (starting at 0) to some object. 基本上,列出“映射”顺序整数(从0开始)到某个对象。 In that way, they behave a lot more like a dynamic array in other languages. 这样,它们的行为就更像其他语言中的动态数组。 In fact, Cpython implements them as overallocated arrays in C. 实际上,Cpython将它们实现为C中的过度分配数组。

dict map hashable keys to an object. dict将可哈希键映射到对象。 They're implemented using hash tables. 它们是使用哈希表实现的。


Also note that starting from python2.7, you can use the {} to create sets as well which are another (fundamental) type. 另请注意,从python2.7开始,您也可以使用{}创建另一个(基本)类型的集合。 Review: 评论:

[] #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. 

On python 2.x 在python 2.x上

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

On python 3.x 在python 3.x上

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM