统计列表中的字典
方法一:
a = [{'appreciation_id': 1341, 'level_name': 'S'}, {'appreciation_id': 1341, 'level_name': 'S'},
{'appreciation_id': 1341, 'level_name': 'S'}, {'appreciation_id': 1342, 'level_name': 'A'},
{'appreciation_id': 1342, 'level_name': 'A'}, {'appreciation_id': 1342, 'level_name': 'A'},
{'appreciation_id': 1342, 'level_name': 'A'}, {'appreciation_id': 1343, 'level_name': 'B'},
{'appreciation_id': 1344, 'level_name': 'C'}, {'appreciation_id': 1345, 'level_name': 'E'},
{'appreciation_id': 1351, 'level_name': 'F'}]
from collections import Counter
res = Counter([i.get('level_name') for i in a if a])
print(res)
输出:
Counter({'A': 4, 'S': 3, 'B': 1, 'C': 1, 'E': 1, 'F': 1})
方法二:
a = [{'appreciation_id': 1341, 'level_name': 'S'}, {'appreciation_id': 1341, 'level_name': 'S'},
{'appreciation_id': 1341, 'level_name': 'S'}, {'appreciation_id': 1342, 'level_name': 'A'},
{'appreciation_id': 1342, 'level_name': 'A'}, {'appreciation_id': 1342, 'level_name': 'A'},
{'appreciation_id': 1342, 'level_name': 'A'}, {'appreciation_id': 1343, 'level_name': 'B'},
{'appreciation_id': 1344, 'level_name': 'C'}, {'appreciation_id': 1345, 'level_name': 'E'},
{'appreciation_id': 1351, 'level_name': 'F'}]
result = {}
for i in a:
if i.get('level_name') not in result:
result[i.get('level_name')] = 1
else:
result[i.get('level_name')] += 1
print(result)
方法三:
a = [{'appreciation_id': 1341, 'level_name': 'S'}, {'appreciation_id': 1341, 'level_name': 'S'},
{'appreciation_id': 1341, 'level_name': 'S'}, {'appreciation_id': 1342, 'level_name': 'A'},
{'appreciation_id': 1342, 'level_name': 'A'}, {'appreciation_id': 1342, 'level_name': 'A'},
{'appreciation_id': 1342, 'level_name': 'A'}, {'appreciation_id': 1343, 'level_name': 'B'},
{'appreciation_id': 1344, 'level_name': 'C'}, {'appreciation_id': 1345, 'level_name': 'E'},
{'appreciation_id': 1351, 'level_name': 'F'}]
result = {}
for i in a:
result.setdefault(i.get('level_name'), 0)
result[i.get('level_name')] += 1
print(result)
统计纯列表
方法一:
a = ['h', 'h', 'e', 'a', 'a']
result = {}
for i in a:
result.setdefault(i, 0)
result[i] += 1
print(result)
输出:
{'h': 2, 'e': 1, 'a': 2}
方法二:
a = ['h','h','e','a','a']
result = {}
for i in a:
if i not in result:
result[i] = 1
else:
result[i] += 1
print(result)
输出:
{'h': 2, 'e': 1, 'a': 2}
方法三:
num = [1, 1, 2, 2, 3, 4, 4, 1]
set_num = set(num) # set()会创建一个无序且不重复的集合
for i in set_num:
print('%d--数量:%d' % (i,num.count(i)))
方法四:
from collections import Counter
num = [1, 1, 2, 2, 3, 4, 4, 1]
new_num = Counter(num)
print(new_num)
方法五:
num = [1, 1, 2, 2, 3, 4, 4, 1]
dic_num = {}
for i in num:
dic_num[i] = num.count(i)
for key,value in dic_num.items():
print('%s--数量%d' % (key,value))
|