在实际工作中,有时候我们需要对数据进行分类统计数量,一种是SQL利用group by进行统计,另一种可以用Python代码行来进行操作
- datas = [{'name': 'jack', 'gender': '男', 'address': '深圳'}, {'name': 'tom', 'gender': '男', 'address': '东莞'},
- {'name': 'jerry', 'gender': '男', 'address': '广州'}, {'name': 'alisi', 'gender': '女', 'address': '深圳'},
- {'name': 'rose', 'gender': '女', 'address': '北京'}, {'name': 'anna', 'gender': '女', 'address': '北京'},
- {'name': 'jack', 'gender': '男', 'address': '深圳'}, {'name': 'tom', 'gender': '男', 'address': '东莞'},
- {'name': 'jerry', 'gender': '女', 'address': '广州'}, {'name': 'alisi', 'gender': '女', 'address': '深圳'},
- {'name': 'rose', 'gender': '男', 'address': '北京'}, {'name': 'anna', 'gender': '女', 'address': '北京'}]
- def statistical_data(datas):
- """
- :return: dict
- """
- res_dict = {}
- for data in datas:
- city = data.get('address')
- if city not in res_dict:
- res_dict[city] = 1 # 初始数量1
- else:
- res_dict[city] += 1 # 相同key对应的数量+1
- return res_dict
-
- result = statistical_data(datas)
- print(result)
- # {'深圳': 4, '东莞': 2, '广州': 2, '北京': 4}
- def statistical_data(datas):
- """
- :return: dict
- """
- res_dict = {}
- for data in datas:
- gender = data.get('gender')
- if gender == '男':
- num_list = [1, 0] # 第一个位置表示男的数量
- index = 0
- else:
- num_list = [0, 1] # 第二个位置表示女的数量
- index = 1
- city = data.get('address')
- if city not in res_dict:
- res_dict[city] = num_list # 初始列表
- else:
- res_dict[city][index] += 1 # 相同key对应的位置数量+1
- return res_dict
-
- result = statistical_data(datas)
- print(result)
- # {'深圳': [2, 2], '东莞': [2, 0], '广州': [1, 1], '北京': [1, 3]}
- res = {'深圳': [2, 2], '东莞': [2, 0], '广州': [1, 1], '北京': [1, 3]}
- result = dict(sorted(res.items(), key=lambda x: sum(x[1]), reverse=True))
-
- print(result)
- # {'深圳': [2, 2], '北京': [1, 3], '东莞': [2, 0], '广州': [1, 1]}
这类代码也可以封装一下,作为一个常用的公共类视图
- class PublicFunc(object):
- def __init__(self, datas):
- self.datas = datas
-
- def statistical_data(self):
- """
- :return: dict
- """
- res_dict = {}
- for data in self.datas:
- city = data.get('address')
- if city not in res_dict:
- res_dict[city] = 1 # 初始数量1
- else:
- res_dict[city] += 1 # 相同key对应的数量+1
- return res_dict
-
- def style_data(self,datas):
- """
- :param datas: dict
- :return: dict
- """
- name_list = []
- value_list = []
- for k,v in datas.items():
- name_list.append(k)
- value_list.append(v)
-
- return {'name':name_list,'value':value_list}
-
- public_func = PublicFunc(datas)
- res = public_func.statistical_data()
-
- result = dict(sorted(res.items(), key=lambda x: x[1], reverse=True))
-
- print(result)
- # {'深圳': 4, '北京': 4, '东莞': 2, '广州': 2}
- result2 = public_func.style_data(result)
- print(result2)
- # {'name': ['深圳', '北京', '东莞', '广州'], 'value': [4, 4, 2, 2]}