我试图理解两个例子之间的区别。
{"".join(MORSE[ord(c) - ord('a')] for c in word)
for word in words}
输出:{'--...-.', '--...--.'}
当我使用dict时,似乎使用函数set()。
{{1}}
输出:{{1}}
答案 0 :(得分:4)
大括号({
,}
)用于创建集和词组,具体取决于内容是单个元素列表还是key: value
对列表。< / p>
>>> 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'>
答案 1 :(得分:1)
第一个表达式用括号括起来,是list comprehension,产生list object。第二个表达式用大括号括起来,是一个set comprehension,它产生一个只包含唯一元素的set对象。
dict comprehension语法可以类似地用于创建dict:
{x: x+1 for x in [1,2,3]}
# {1: 2, 2: 3, 3: 4}