python实战-字典使用

时间:2015-05-10 18:59:36   收藏:0   阅读:155

python实战-字典使用


使用字典统计字符出现次数

#! /usr/bin/env python
#coding:utf-8
#定义一个函数,接收字符串,统计出每个字符的出现次数
#实现思路:字典实现,看字符是否在字典中,不在则计入字典,否则+1。
def histogram(str):
    dic = dict()
    for c in str:
        if c not in dic:
            dic[c] = 1 #add
        else:
            dic[c]+=1 #update
    return dic
print histogram(‘helloworld‘)
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!