2014-12-03 30 views
0

我之前已经问过类似的问题,所以我很抱歉,但是我读回任务并误解了最初的需求。排序字典键内的列表 - 从列表中获得最高分3

因此,基于我在这里获得的反馈,这是我使用的代码:

def task3(): 
    classList = {} 
    classSearch = input("Which class would you like to interrogate? ") 
    try: 
     with open("answers " + classSearch + ".txt", 'rb') as handle: 
      classList = pickle.loads(handle.read()) 
    except IOError as error: 
     print ("Sorry, this file does not exist") 

    sortOption = int(input("Would you like sort the students in alphabetical order? Enter 1\n Would you like to sort the students by highest score? Enter 2 \nWould you like to sort students by their average score?Enter 3\n")) 
    if sortOption == 1: 
     x = sorted(classList.items()) 
     for key, value in x: 
      value.sort() 
      value.reverse() 
     print (x) 

所以我真正需要做的是输出每个学生的最高分,是按字母顺序排序名称。在classList字典里面是学生名字,然后是包含他们在测验中收到的最后3个分数的列表。对于多名学生来说这显然是重复的。任何帮助将大规模赞赏。

+0

标准字典是无序的。这意味着你无法对其进行分类。我想你需要一个有序的词典。 https://docs.python.org/2/library/collections.html#collections.OrderedDict – 2014-12-03 10:56:45

+0

谢谢,我自己最后通过打印索引位置来修复它0 – RH84 2014-12-03 12:27:23

回答

0

像这样的事情应该工作,假设输入是完全无序:

for name,highscore in [(student,max(classList[student])) for student in sorted(classList.keys())]: 
    print name,highscore 

ETA

按照要求,提供了一个解释。

classList是一个dict,每个成员由一个键(学生的名字)和一个值(该学生的分数列表)组成。

我建议的代码遍历预先排序的列表,理解包含学生姓名和该学生最高分数的元组,并依次打印每个元组。

列表理解完成这里的所有工作。

classList.keys()产生一个包含学生姓名的列表。在这种情况下,内置的sorted函数返回相同的按字母顺序排序。

列表理解就像一个for循环,遍历键列表并构建一个元组列表。

你也可以说

sortedNames = sorted(classList.keys()) 
for student in sortedNames: 
    high_score = max(classList[student]) 
    print student, high_score 
+0

嗨,我处于与OP类似的情况。此代码为我工作。你能解释一下吗,因为我不明白吗? – Kaiylar 2016-05-21 10:19:03

+0

另外,哪些是变量?学生是一个变量吗?如果不是,那是什么? – Kaiylar 2016-05-21 11:20:15

+0

@Kaiylar,变量有点不恰当,我认为它是Python的标签? – selllikesybok 2016-05-21 12:26:51

相关问题