Pythonlist列表groupby分组⽤法Python list列表groupby分组⽤法
注意分组之前应先使⽤分组字段先排好序
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))
print("⾃定义分组key")
# ⾃定义分组key
def g(x):
if(x['age']>0)and(x['age']<=10):
return'small'
elif(x['age']>10)and(x['age']<=20):
return'mid'
else:
return'max'
user_sort =sorted(user_list, key=lambda x: x["age"])
user_group = groupby(user_sort, key=g)
for key, group in user_group:
print(key,list(group))
运⾏结果
groupby分组
('⼥', 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}]
#⾃定义分组key
small [{'uid': 1, 'sex':'男', 'age': 10}, {'uid': 2, 'sex':'男', 'age': 10}]
mid [{'uid': 3, 'sex':'男', 'age': 20}, {'uid': 4, 'sex':'⼥', 'age': 20}]
max [{'uid': 4, 'sex':'⼥', 'age': 31}]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。