python - 如何根据分数生成一个包含两个学生姓名的元组列表?
问题描述
names = ["Rachael","Nick","John","May"]
scores = [[100,50,50],[75,50,100],[100,100,50],[30,90,55]]
added_scores = []
tuplist = []
for score in scores:
added_scores.append(sum(score))
#I'm trying to add the scores to find their sum-easier than tyring to find similar scores individually
tuplist = tuple(zip(names,added_scores))
from operator import itemgetter
tuplist = sorted(tuplist,key=itemgetter(1))
#Here I wanted to sort the list of tuples based on lowest to highest score
print(added_scores)
print(tuplist)
我的目标是根据他们的分数将两个学生分组。我需要将分数最相似的学生组合在一起,我需要为我所有的学生这样做。我需要一个元组的输出,例如。[("May","Rachael"), ("Nick","John")],这对学生的小组作业得分最相似(May 得 175 分,Rachael 得 200 分,Nick 得 225 分,以及约翰与 250)。我只需要知道如何从元组中连续提取名称以生成每个元组有两个名称的新元组列表。
解决方案
尝试这样的事情:
tuplist = sorted(tuplist, key=lambda x: x[1])
names = [x[0] for x in tuplist]
pairs = tuple(zip(names[::2], names[1::2]))
这首先对元组进行排序(就像您所做的那样,但不需要另一个模块)。然后,我们把所有的名字都拉回来。最后,我们通过从第一个开始的每个第二个名称和从第二个开始的每个第二个名称来配对相邻的名称。
编辑:这是一个更清洁的解决方案(完整代码):
names = ["Rachael","Nick","John","May"]
scores = [[100,50,50],[75,50,100],[100,100,50],[30,90,55]]
added_scores = [sum(x) for x in scores]
sortednames = [x for y,x in sorted(zip(added_scores, names))]
pairs = tuple(zip(sortednames[::2], sortednames[1::2]))
推荐阅读
- node.js - base64 转 S3 多张图片
- key-bindings - 如何重置鱼壳键绑定
- node.js - 如何知道何时运行 redis.quit()
- ios - 如何在 iOS 中使用 Firebase 删除已发送的远程推送通知?
- javascript - Express.js 服务器:使用中间件的 PUT 请求
- java - 成功登录后 Spring Boot Active Directory 身份验证不重定向
- c# - Asp.Net C# mvc。运行编译的应用程序
- java - 模拟 openInputStream 读取方法
- ios - 如何在 Swift 的 UIButton 扩展中使用 UIButton 实例作为参数创建函数?
- javascript - 如何在jquery ajax中向成功函数发送附加参数