简体   繁体   中英

Display list sorted alphabetically

We're trying to create a function that takes the input, some data containing the following information: ID number, Name, as well as a number of columns containing the grades for different assignments, and then sorts the data alphabetically (according to the name) and then displays the data with a column added that also displays the final grade (that we calculate with another function we made). We've tried writing the following code, but can't get it to work... The error-message given is "names = GRADESdata[:,1].tolist() TypeError: string indices must be integers".

Can anyone help us to figure out how to get it working?

def listOfgrades(GRADESdata):

    names = GRADESdata[:,1].tolist()
    names = names.sort(names)
    assignments = GRADESdata[:,2::]
    final_grades = computeFinalGrades(GRADESdata)
    final_grades = np.array(final_grades.reshape(len(final_grades),1))

    List_of_grades = np.hstack((GRADESdata, final_grades))

    NOofColumns = np.size(GRADESdata,axis = 1)
    display = np.zeros(NOofColumns)

    for i in names:
        display = np.vstack((display,GRADESdata[GRADESdata[:,1] == i]))

    grades = display[1::,2:-1]
    gradesfinal = display[1::,-1]

    #Column titles
    c = {"Student ID": GRADESdata[1::,0], "Name": GRADESdata[1::,1]}

    for i in range(GRADESdata.shape[1]):
        c["Assign.{}".format(i+1)] = GRADESdata[:,i]

    c["Final grade"] = final_grades

    d = pd.DataFrame(c)

    print(d.to_string())


    display = np.array([student_list, names, assignments, final_grades])
    return display

The expected output is something like this (with the data below ofc):

ID number     Name     Assignment 1     Assignment 2      Final Grade

EDIT: the data input is a .csv file containing the following data:ID number,Name,Assignment 1,Assignment 2, etc.

From looking at .tolist() , I assume the data structure you're supposed to use is numpy.ndarray.

I managed to replicate the error with the following code:

print("12354"[:,1].tolist())

which makes sense if you're using a file name as input - and that's your mistake. In order to fix this problem, you need to implement a string parser at the beginning or outside the function.

Add the following to your code at the beginning:

file=open(GRADESdata,"r")
data=file.read()
file.close()
list1=data.split("\n")#Replace \n with appropriate line separator
list2=[e.split(",") for e in list1]
GRADESdata=numpy.array(list2)

The comma in

names = GRADESdata[:,1].tolist()

is not a valid character. the part between [: and ] must be an integer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM