pythonjythonjes

Altering csv function to return specific data?


The function below takes a csv file that is formatted grade type,grade type number,grade. Example the first 10 are assignment,assignment number,grade. The function puts these first 10 into a list.

What I'm trying to get the function to do is return:
highest grade,assignment number and
lowest grade,assignment number

def assigment(file):
  res=[]
  f = open(file,'r+')
  reader = csv.reader(f)
  for i, line in enumerate(reader):
      if i < 10:    
         res.append((line[0],int(line[1]),int(line[2])))
         print max(res)

Solution

  • If index [2] is the grade for each assignment, and it is numeric, you can use the sort function as follows:

    import csv
    
    
    def assigment(file):
    
        res = []
    
        with open(file) as f:
            reader = csv.reader(f)
    
            for line in reader[:10]:
                res.append((line[0],int(line[1]),int(line[2])))
    
        res.sort(key= lambda x: x[2])
    
        max = res[-1]
        min = res[0]