统计list中各种类型的个数,统计list类型个数,#coding=utf-


#coding=utf-8print 'I am ',__name__def getClassify(lists):    res ={}    for item in lists:        if isinstance(item,int):            res['int'] = res.get('int', 0) + 1        elif isinstance(item,basestring):            res['str'] = int(res.get('str', 0)) + 1        elif isinstance(item,list):            res['list'] = int(res.get('list', 0)) + 1        elif isinstance(item,tuple):            res['tuple'] = int(res.get('tuple', 0)) + 1        elif isinstance(item,dict):            res['dict'] = int(res.get('dict', 0)) + 1        else:            res['others'] = int(res.get('others', 0)) + 1    return resdef getClassify2(lists):    typeflag = type(lists[0])    rest ={}    rest[typeflag] = 1    for each in lists[1:]:        if type(each) == typeflag:            rest[typeflag] = rest.get(typeflag,0) + 1        else:            typeflag = type(each)            rest[typeflag] = rest.get(typeflag,0) + 1    return restif __name__ == "__main__":    lists = [1,2,'2','3','a',(1,2,3),[3,4,5,6],{'spam':'ham'},None]    print getClassify(lists)    print getClassify2(lists)

评论关闭