个人拙见,就当一次练手,没有使用第三方库
def func(data, column1, column2):
column1_values=[]
for row in data:
value1=row[column1]
if value1 not in column1_values:
column1_values.append(value1) #column1_values==["一班", "二班"]
data1=[]
for c1_value in column1_values:
rows=list(filter(lambda row: row[column1]==c1_value, data))
c2_value=[]
for r in rows:
r1=r.copy() #直接改rows会导致data变动,因此必须把rows的元素copy到新变量
r1.pop(column1)
c2_value.append(r1)
new_row={column1:c1_value, column2:c2_value}
data1.append(new_row)
return data1
>>> data=[
{"class":"一班","name":"小明","age":"18","height":"180cm","sex":"男"},
{"class":"一班","name":"小文","age":"17","height":"170cm","sex":"女"},
{"class":"二班","name":"张三","age":"18","height":"180cm","sex":"男"},
{"class":"二班","name":"李四","age":"17","height":"170cm","sex":"女"},
]
>>> data1=func(data, column1="class", column2="info")
>>> print(data1)
[{'class': '一班', 'info': [{'name': '小明', 'age': '18', 'height': '180cm', 'sex': '男'}, {'name': '小文', 'age': '17', 'height': '170cm', 'sex': '女'}]}, {'class': '二班', 'info': [{'name': '张三', 'age': '18', 'height': '180cm', 'sex': '男'}, {'name': '李四', 'age': '17', 'height': '170cm', 'sex': '女'}]}]
|