尝试按特定格式对3种类型的数据进行排序

时间:2016-05-06 18:50:13

标签: python sorting

所以我遇到以下格式排序数据的问题: 名称,Score1,Score2,Score3存储在文本文件中。

例如:

Zac,0,0,0

Zac,0,0,0

Zac,0,0,0

Zac,0,0,0

我需要按字母顺序,最高分和平均分数对其进行排序,但我不确定如何做到这一点。

有人可以帮助我或给我一些指示,因为我不知道从哪里开始?

这是任务:

任务3 老师想要使用学生参加这些测验的结果来记录他们的表现。系统应存储每个学生的最后三个分数。老师希望能够输出特定班级的测验结果,排序:

•按字母顺序排列,每个学生的考试成绩最高

•按最高分,从最高到最低

•按平均得分,从最高到最低。

到目前为止我的代码:

import random
import csv

User = input("Student (s) / Teacher (t):")

if User == "s" or "S":
    classList = []

    Name = input("What is your name? ")
    Class = int(input("Please enter your class: "))

    CompletedTimes = int(0)
    while CompletedTimes <= 2:
        NumberQuestion = 0
        Score = int(0)
        while NumberQuestion < 10:
            Symbol = random.randrange (1, 4)
            if Symbol == 1:
                number1 = random.randrange(1, 25)
                number2 = random.randrange(1, 25)
                SetQuestion = (number1 * number2)
                print (number1, "x", number2)
                while True:
                            try:
                                Answer = int(input("Answer: "))
                                break
                            except ValueError:
                                print("Enter a number")
                if Answer == SetQuestion:
                    print ("Correct. +1")
                    Score = (Score + 1)
                    NumberQuestion = (NumberQuestion + 1)
                else:
                    print ("incorrect")
                    NumberQuestion = (NumberQuestion + 1)

            if Symbol == 2:
                number1 = random.randrange(1, 25)
                number2 = random.randrange(1, 25)
                SetQuestion = (number1 + number2)
                print (number1, "+", number2)
                while True:
                            try:
                                Answer = int(input("Answer: "))
                                break
                            except ValueError:
                                print("Enter a number")
                if Answer == SetQuestion:
                    print ("Correct. +1")
                    Score = (Score + 1)
                    NumberQuestion = (NumberQuestion + 1)
                else:
                        print ("incorrect")
                        NumberQuestion = (NumberQuestion + 1)

            elif Symbol == 3:
                number1 = random.randrange(1, 25)
                number2 = random.randrange(1, 25)
                SetQuestion = (number1 - number2)
                print (number1, "-", number2)
                while True:
                            try:
                                Answer = int(input("Answer: "))
                                break
                            except ValueError:
                                print("Enter a number")
                if Answer == SetQuestion:
                    print ("Correct. +1")
                    Score = (Score + 1)
                    NumberQuestion = (NumberQuestion + 1)
                else:
                    print ("incorrect")
                    NumberQuestion = (NumberQuestion + 1)
        classList.append(Score)
        print ("Your final score is: ", Score)
        CompletedTimes = (CompletedTimes + 1)

    classList = str(classList)
    classList = str(classList)[1:-1]

    Class = str(Class)
    Class = (Class+'.csv')
    thefile = open(Class, 'w')
    thefile.write(Name + ',')
    thefile.write(classList)
    thefile.close()

elif User == "t" or 'T':
    CONTINUE CODE HERE

2 个答案:

答案 0 :(得分:0)

我会有一个像这样的对象:

class Grade(object):
    def __init__(self, name, score1, score2, score3):
        self.name = name
        self.score1 = score1
        self.score2 = score2
        self.score3 = score3

    @property
    def average(self):
        return float(self.score1 + self.score2 + self.score3) / 3.0

    @property
    def highest(self):
        return max([self.score1, self.score2, self.score3])

    def __repr__(self):
        return "<Grade({}, [{}, {}, {}]) object at 0x{:08X}>".format(self.name, self.score1, self.score2, self.score3, id(self))

    def __str__(self):
        return "Grade({}, [{}, {}, {}])".format(self.name, self.score1, self.score2, self.score3)    

x = Grade("Bob", 85, 92, 90)
y = Grade("Alice", 80, 75, 95)

grades = [x, y]

alphabetical = sorted(grades, key=lambda g: g.name)
highest_score = sorted(grades, key=lambda g: g.highest, reverse=True)
average_score = sorted(grades, key=lambda g: g.average, reverse=True)

def display(l):
    print([str(item) for item in l])

display(alphabetical)  # => ['Grade(Alice, [80, 75, 95])', 'Grade(Bob, [85, 92, 90])']
display(highest_score)  # => ['Grade(Alice, [80, 75, 95])', 'Grade(Bob, [85, 92, 90])']
display(average_score)  # => ['Grade(Bob, [85, 92, 90])', 'Grade(Alice, [80, 75, 95])']

答案 1 :(得分:0)

假设您的文件名为“data.csv”并具有以下文本:

Zac, 0, 0, 0
Zac, 4, 5, 6
Zac, 0, 0, 0
Zac, 1, 2, 3
Al, 1, 2, 3

然后我们可以构建我们的代码:

import csv  # import csv reader
with open("data.csv", 'r') as f:  # open the file
   reader = csv.reader(f)         # read the data
   lines = [[l[0], float(l[1][1:]), float(l[2][1:]), float(l[3][1:]) for l in reader]
# sort the list
sorted(lines, key = lambda x: (x[0], max(x[1:3]),sum(x[1:3])/float(len(x[1:3]))))
# [['Al', 1.0, 2.0, 3.0],
# ['Zac', 0.0, 0.0, 0.0],
# ['Zac', 0.0, 0.0, 0.0],
# ['Zac', 1.0, 2.0, 3.0],
# ['Zac', 4.0, 5.0, 6.0]]

因为你的文件没有完美格式化csv(逗号之间有空格),我们必须做一些额外的解析。这是 lines =

所发生情况的细分
  1. reader包含文件中的每一行,以便我们可以遍历它
  2. for l in reader说,对于读者中的每一行,都要采取行动
  3. 最外面的括号表示我们希望将这些操作的结果存储在列表中
  4. 最里面的括号表示对于阅读器中的每一行,我们要构建一个包含行中数据的列表
  5. 为了进行数学运算,我们必须将字符串转换为intfloat类型
  6. i[0]访问第一个名为
  7. 的元素
  8. i[1]是第二个元素,当前是一个字符串 - '0'
  9. i[1][1:]说第二个元素,从第二个元素到字符串结尾的所有内容都是'0'
  10. float([1][1:])表示给定字符串'0',将其转换为浮点类型
  11. 然后我们对列表进行排序。首先,它将对名称进行排序,然后对最高分进行排序,然后对平均值进行排序。

    Sort list by multiple attributes