1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| from itertools import groupby
user_list = [ {"uid": 1, "sex": "男", "age": 10}, {"uid": 3, "sex": "男", "age": 20}, {"uid": 4, "sex": "女", "age": 20}, {"uid": 4, "sex": "女", "age": 31}, {"uid": 2, "sex": "男", "age": 10} ]
user_sort = sorted(user_list, key=lambda x: (x["sex"], x["age"]))
user_group = groupby(user_sort, key=lambda x: (x["sex"], x["age"])) for key, group in user_group: print(key, list(group)) """ ('女', 20) [{'uid': 4, 'sex': '女', 'age': 20}] ('女', 31) [{'uid': 4, 'sex': '女', 'age': 31}] ('男', 10) [{'uid': 1, 'sex': '男', 'age': 10}, {'uid': 2, 'sex': '男', 'age': 10}] ('男', 20) [{'uid': 3, 'sex': '男', 'age': 20}] """
|