首页 > 解决方案 > 如何根据分数生成一个包含两个学生姓名的元组列表?

问题描述

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)。我只需要知道如何从元组中连续提取名称以生成每个元组有两个名称的新元组列表。

标签: pythonlisttuples

解决方案


尝试这样的事情:

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]))

推荐阅读