用setdefault()方法去写一个小程序,计算一个字符串中每个字符出现的次数,并打印改字符与次数
message = "Hello China, my name is Leilani. I love China"
count = {}
for character in message:
count.setdefault(character, 0)
count[character] += 1
print(count)
打印结果:
{'H': 1, 'e': 4, 'l': 4, 'o': 2, ' ': 8, 'C': 2, 'h': 2, 'i': 5, 'n': 4, 'a': 4, ',': 1, 'm': 2, 'y': 1, 's': 1, 'L': 1, '.': 1, 'I': 1, 'v': 1}
如果程序中import pprint模块,它们将偏亮打印一个字典的键值对:
import pprint
message = "Hello China, my name is Leilani. I love China"
count = {}
for character in message:
count.setdefault(character, 0)
count[character] += 1
pprint.pprint(count)
打印结果:
{' ': 8,
',': 1,
'.': 1,
'C': 2,
'H': 1,
'I': 1,
'L': 1,
'a': 4,
'e': 4,
'h': 2,
'i': 5,
'l': 4,
'm': 2,
'n': 4,
'o': 2,
's': 1,
'v': 1,
'y': 1}