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