计算字符数量-代码实现
①单个字符 message='It was a bright cold day in April,and the clocks were striking thirteen.' count={} for i in message: count.setdefault(i,0) count[i]=count[i]+1 print(count)
{'I': 1, 't': 6, ' ': 12, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1} ②字符串 message=['a','a','bb'] count={} for i in message: count.setdefault(i,0) count[i]=count[i]+1 print(count) {'a': 2, 'bb': 1}

浙公网安备 33010602011771号