重写字典理解

2024-06-28 15:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想知道有没有可能用字典来理解?在

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

Tags: inforif字典字母单词次数lower
2条回答

另一个使用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})

或者另一个不使用进口的。在

^{pr2}$

当然有可能。在

occurences = {k: word.count(k) for k in word}

print(occurences)

{'a': 2, 'b': 1, 'c': 1, 'd': 1}

或者使用^{}。在

^{pr2}$

相关问题 更多 >