方法一:python
list1 = ['a', 'a', 'b', 'c', 'c', 'c', 'c'] dict_cnt = {} for value in list1: dict_cnt[value] = dict_cnt.get(value, 0) + 1 print(dict_cnt)
方法二:code
list1 = ['a', 'a', 'b', 'c', 'c', 'c', 'c'] dict_cnt = {} for item in list1: if item in dict_cnt: # 直接判斷key在不在字典中 dict_cnt[item] += 1 else: dict_cnt[item] = 1 print(dict_cnt)