从python

时间:2015-10-29 21:05:47

标签: python list sorting

我已经完成了一项任务,我必须对测试中的分数进行排序,这些分数保存在txt文件中。我必须按字母顺序对它们进行排序,只显示每个学生的高分数,用最高到最低的名称对分数进行排序,然后将平均分数从最高到最低排序。我不知道除了使用sorted()之外,还没有按照我想要的方式对它进行排序。

the txt file looks like this:
James
3
8
4 
Jim 
6
2
10 
Tom
3
7
10 
Bob 
10
8
6
    This is my code:
class1 =[]
filename = 'class1.txt'
f = open (filename,'r')
class1 = f.read().splitlines()

class2 =[]
filename = 'class2.txt'
f = open (filename,'r')
class2 = f.read().splitlines()

class3 =[]
filename = 'class3.txt'
f = open (filename,'r')
class3 = f.read().splitlines()
def Menu():
    print(" How would you like the results sorted")
    print("Enter 1 to sort alphabetically with each students highest score    for the tests")
    print("Enter 2 to sort by the highest score highest to lowest")
    print("Enter 3 to sort by the average score highest to lowest")


WhichClass = input("What class would you like to sort 1,2 or 3")
while int(WhichClass)>3:
    WhichClass = input("Please enter 1,2 or 3")
if WhichClass == '1':
    Menu()
    MenuChoice = input()
    while int(MenuChoice)>3:
        MenuChoice = input()
    if MenuChoice == '1':
         print(sorted(class1))

但是这段代码就像这样排序:

What class would you like to sort 1,2 or 31
How would you like the results sorted
Enter 1 to sort alphabetically with each students highest score for the tests
Enter 2 to sort by the highest score highest to lowest
Enter 3 to sort by the average score highest to lowest
1
['10', '10 ', '10 ', '2', '3', '3', '4 ', '6', '6', '7', '8', '8', 'Bob ',   'James', 'Jim ', 'Tom']

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:0)

在sort:

中添加一个key = int
sorted(class1, key=int)

您可以使用的可能性:

>>> class1 = ['James', '3', '8', '4']
>>> classDict = {}
>>> classDict[class1.pop(0)] = class1
>>> classDict
{'James': ['3', '8', '4']}
>>> classDict['James']
['3', '8', '4']
>>> sorted(classDict['James'], key=int)
['3', '4', '8']
>>> sorted(classDict['James'], key=int, reverse=True)
['8', '4', '3']