gpt4 book ai didi

python - dict.setdefault() 如何统计字符数?

转载 作者:太空宇宙 更新时间:2023-11-04 00:28:57 26 4
gpt4 key购买 nike

我从 Automate the boring stuff with 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com