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