Python参考题解(简单)
info = [{"name": "AD", "group": "full stack", "score": 99},
{"name": "蚊子", "group": "backend", "score": 93},
{"name": "北北", "group": "frontend", "score": 90},
{"name": "AD", "group": "full stack", "score": 88},
{"name": "蚊子", "group": "backend", "score": 101}]
def the_best(info) -> dict:
names = []
for item in info:
name = item['name']
if name not in names:
names.append(name)
continue
grouped = []
for name in names:
li = [x for x in info if x['name'] == name]
grouped.append(li)
best_li = []
for item in grouped:
maxs = max(item, key=lambda x:x['score'])
best_li.append(maxs)
return best_li
assert the_best(info) == [{"name": "AD", "group": "full stack", "score": 99},
{"name": "蚊子", "group": "backend", "score": 101},
{"name": "北北", "group": "frontend", "score": 90}]
思路:使用for循环,三步走。第一步,获取所有唯一的姓名列表;第二步,根据姓名分别收集各自的信息,相当于分组;第三步,针对每个人保留其最佳成绩信息。
代码解析:
names = []
for item in info:
name = item['name']
if name not in names:
names.append(name)
continue
上面这一段是使用循环,求出去重后,实际选手的名字,得到结果:[‘AD’, ‘蚊子’, ‘北北’]。之所以没有直接用集合set是因为断言中约定了排列顺序。
grouped = []
for name in names:
li = [x for x in info if x['name'] == name]
grouped.append(li)
上面这一段,遍历姓名列表,分别将每个人的成绩信息进行分组,以便后面使用内置函数max()
来求大最值。
grouped结果是:
[
[
{'name': 'AD', 'group': 'full stack', 'score': 99},
{'name': 'AD', 'group': 'full stack', 'score': 88}
],
[
{'name': '蚊子', 'group': 'backend', 'score': 93},
{'name': '蚊子', 'group': 'backend', 'score': 101}
],
[{'name': '北北', 'group': 'frontend', 'score': 90}]
]
下面这段,对分组的数据,按照分数作为规则,保留最大的那一项。
best_li = []
for item in grouped:
maxs = max(item, key=lambda x:x['score'])
best_li.append(maxs)
return best_li