繁体   English   中英

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

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

之间有什么区别:

dictionary = []

dictionary = {}

假设字典中有字符串内容?

在第一种情况下,您在创建list而在另一种情况下,您在做dict list对象是序列,dict对象是映射 看看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. 

在python 2.x上

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

在python 3.x上

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

暂无
暂无

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

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