python-3.x “count[character] = count[character] +1”在这个程序中对一个句子中的字母计数做了什么

68de4m5k  于 2023-01-03  发布在  Python
关注(0)|答案(2)|浏览(141)

下面的代码行用于计算语句中分配给变量"message"的单个字母的数量。

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)

代码成功运行,输出如下
x一个一个一个一个x一个一个二个x
请问这部分代码在程序中做什么

count[character] = count[character] + 1
pftdvrlh

pftdvrlh1#

您在问题中提到的代码行:
1.提取给定键(字符)的现有字典值,并将其递增1 count[character] + 1
1.更新键count[character] =的值。
由于setdefault方法返回给定键的当前值,因此实际上可以使代码更短一些:

message = 'It was a bright cold day in April, and the clocks were striking thirteen'

count = {}

for character in message:
    count[character] = count.setdefault(character, 0) + 1

print(count)
mnemlml8

mnemlml82#

count[character] = count[character] + 1本质上是将当前字符的计数加1,所以首先,setdefault()是一个函数,它检查当前计数是否存在于字典中,如果不存在,则将其添加默认值0,然后在字典中,那个字符会加1。让我给予个例子。如果我们在第一个message中的第(零)个字符,'I',setdefault()检查'I'是否已经在字典中,然后将其值与0相加。然后递增1。这意味着字典中'I'的值现在是1

相关问题