类型1
s1 = 'jason say hello hello hello big baby baby baby sb sb jason jason' # 统计每个单词的个数 # 1.定义一个空字典 data_dict = {} # 2.如果是拿每个单词 则使用切割 new_list = s1.split(' ') # ['jason','say',...] # 3.for循环列表中每个单词 for i in new_list: # jason say hello hello ... if i in data_dict: # i=jason {} # 取出i对应的值自增1即可 data_dict[i] += 1 else: # 新增一组键值对 data_dict[i] = 1 # data_dict['jason'] = 1 {'jason':1} print(data_dict) # {'jason': 3, 'say': 1, 'hello': 3, 'big': 1, 'baby': 3, 'sb': 2}
类型2
s2 = 'jasonsayhello' # 统计每个字符 # data_dict = {} # # 直接循环字符串 # for i in s2: # if i in data_dict: # data_dict[i] += 1 # else: # data_dict[i] = 1 # print(data_dict)