Python 3.x 下面的代码中for循环如何计算字符串中每个字母的出现次数?
在本例中,Python 3.x 下面的代码中for循环如何计算字符串中每个字母的出现次数?,python-3.x,loops,Python 3.x,Loops,在本例中,setdefault()以某种我无法理解的方式使用。它对计算字符有什么帮助 print("Please enter the text : ") message = input() count = {} for i in message: count.setdefault(i,0) count[i] = count[i] + 1 print(count) 此外,在代码中浪费了setdefault的返回值。您可以这样做:对于消息中的i:count[i]=count.
setdefault()
以某种我无法理解的方式使用。它对计算字符有什么帮助
print("Please enter the text : ")
message = input()
count = {}
for i in message:
count.setdefault(i,0)
count[i] = count[i] + 1
print(count)
此外,在代码中浪费了
setdefault
的返回值。您可以这样做:对于消息中的i:count[i]=count.setdefault(i,0)+1
。是的,我得到setdefault()将检查字典中的键并返回值,如果不可用,它将返回默认值。我不明白的是,把它放在for循环中如何帮助计算字符。@ForceBru