将数组缩减为组(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))
希望这些信息对你有所帮助!如果有更多问题,请随时提问。
云+社区沙龙online [新技术实践]
腾讯云GAME-TECH游戏开发者技术沙龙
腾讯技术开放日
DB・洞见
Elastic Meetup Online 第一期
云+社区技术沙龙[第25期]
第五届Techo TVP开发者峰会
云+社区技术沙龙[第29期]
云+社区开发者大会(苏州站)
云+社区技术沙龙[第20期]
领取专属 10元无门槛券
手把手带您无忧上云