簡體   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