重写为字典理解



我想使用字典计算单词中所有字母的出现次数。到目前为止,我已经尝试在循环中添加字典。

我想知道是否可以使用字典理解?

word = "aabcd"
occurrence = {}
for l in word.lower():
    if l in occurrence:
        occurrence[l] += 1
    else:
        occurrence[l] = 1

当然有可能。

使用Counter .

from collections import Counter
c = Counter(word)
print(c)
Counter({'a': 2, 'b': 1, 'c': 1, 'd': 1})

另一种使用 defaultdict 的解决方案。

from collections import defaultdict
occurrence = defaultdict(int)
for c in word.lower():
    occurrence[c] += 1
print(occurrence)
defaultdict(<class 'int'>, {'a': 2, 'b': 1, 'c': 1, 'd': 1})

或者另一个不使用任何导入。

occurrence = {}
for c in word.lower():
    occurrence[c] = occurrence.get(c,0) + 1
print(occurrence)
{'a': 2, 'b': 1, 'c': 1, 'd': 1}

最新更新