我从用 Python 自动化无聊的东西这本书中得到了这段代码,我不明白 setdefault()
方法如何计算唯一字符的数量。
代码:
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
根据这本书,
setdefault()
方法在字典中搜索键,如果未找到则更新字典,如果找到则不执行任何操作。但我不明白
setdefault
的计数行为以及它是如何完成的?输出:
{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'c': 3, 'b': 1, 'e': 5, 'd': 3, 'g': 2,
'i': 6, 'h': 3, 'k': 2, 'l': 3, 'o': 2, 'n': 4, 'p': 1, 's': 3, 'r': 5, 't': 6, 'w': 2, 'y': 1}
请向我解释这一点。
最佳答案
在您的示例中 setdefault() 相当于此代码...
if character not in count:
count[character] = 0
这是(可以说)做同样事情的更好方法:
from collections import defaultdict
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = defaultdict(int)
for character in message:
count[character] = count[character] + 1
print(count)
它有效,因为默认 int 为 0。
一个更好的方法如下:
from collections import Counter
print(Counter(
'It was a bright cold day in April, '
'and the clocks were striking thirteen.'))
关于python - dict.setdefault() 如何计算字符数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46506629/