将数组缩减为组(Grouping Arrays)是一种常见的数据处理操作,通常用于将具有相似特征或属性的数据项分组在一起。这种操作在数据分析、数据挖掘和机器学习等领域中非常有用。
假设我们有一个包含学生信息的数组,我们希望按学生的年级进行分组:
from collections import defaultdict
students = [
{"name": "Alice", "grade": 10},
{"name": "Bob", "grade": 11},
{"name": "Charlie", "grade": 10},
{"name": "David", "grade": 11},
]
grouped_students = defaultdict(list)
for student in students:
grouped_students[student["grade"]].append(student)
print(dict(grouped_students))
{
10: [
{"name": "Alice", "grade": 10},
{"name": "Charlie", "grade": 10}
],
11: [
{"name": "Bob", "grade": 11},
{"name": "David", "grade": 11}
]
}
students = [
{"name": "Alice", "grade": 10},
{"name": "Bob", "grade": None},
{"name": "Charlie", "grade": 10},
]
grouped_students = defaultdict(list)
for student in students:
if student["grade"] is not None:
grouped_students[student["grade"]].append(student)
print(dict(grouped_students))
students = [
{"name": "Alice", "grade": "10"},
{"name": "Bob", "grade": 11},
{"name": "Charlie", "grade": "10"},
]
grouped_students = defaultdict(list)
for student in students:
grade = int(student["grade"]) # 统一转换为整数
grouped_students[grade].append(student)
print(dict(grouped_students))
希望这些信息对你有所帮助!如果有更多问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云