簡體   English   中英

dict和list有什么區別?

[英]What's the difference between dict and list?

我試圖了解兩個示例之間的區別。

MORSE = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.",
             "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]

seen = ["".join(MORSE[ord(c) - ord('a')] for c in word)
            for word in words]

輸出: ['--...-.', '--...-.', '--...--.', '--...--.']

當我使用字典時,似乎使用了set()函數。

{"".join(MORSE[ord(c) - ord('a')] for c in word)
            for word in words}

輸出: {'--...-.', '--...--.'}

花括號( {} )用於創建集合和字典,這取決於內容是單個元素列表還是key: value對列表。

>>> type({"foo", "bar"})
<class 'set'>
>>> type({"foo": "bar"})
<class 'dict'>

同樣,對於理解:

>>> words = ["foo", "bar"]
>>> type({word for word in words})
<class 'set'>
>>> type({word: index for index, word in enumerate(words)})
<class 'dict'>

第一個表達式用方括號括起來,是產生列表對象列表理解 第二個表達式用大括號括起來,是一個set comprehension ,它產生僅包含唯一元素的set對象。

dict理解語法可以類似地用於創建dict

{x: x+1 for x in [1,2,3]}
# {1: 2, 2: 3, 3: 4}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM