简体   繁体   中英

Python/Pandas - For loop only recording final iteration

Obligatory warning - new to Python and Pandas.

I'm having some difficulty executing a for loop that only returns the last value in the list.

I have a .csv file containing information that I'd like to run through CanvasAPI to post user scores. The .csv layout is:

     Name  user_id  Score
0  Name_0     7454   90.0
1  Name_1     7075   96.0
2  Name_2     7377   76.0
3  Name_3     7259   49.0
4  Name_4     7294   48.0
5  Name_5     7491   76.5

My code for executing the loop is:

canvas = Canvas(API_URL, API_KEY)

course = canvas.get_course(9997)

assignment = course.get_assignment(78290)

userlist = [canvas.get_user(user) for user in df['user_id']]
length1 = len(userlist)

for i in range(length1):
    (userlist[i])

scorelist = df['Score']
length2 = len(scorelist)

for x in range(length2):
    (scorelist[x])

submission = assignment.get_submission(userlist[i])
submission.edit(submission={'posted_grade': scorelist[x]})

The loops successfully runs, but only the final row of the .csv is actually scored (for Name_5). What am I missing? Any help greatly appreciated.

The issue is in the last for loop.

    for x in range(length2):
        (scorelist[x])

Each time the loop iterates, scorelist[x] will be the latest value of x. So at the end of the execution, scorelist[x] will be the last value of x.

You'll need to save the value of scorelist[x] each time the loop iterates. One way to do this would be to append the values to a list:

    scores = []
    for x in range(length2):
        scores.append(scorelist[x])

Then you'll need to change the submission at the end to send it all of the scores instead of just the last score.

    for i in range(len(userlist)):
       submission = assignment.get_submission(userlist[i])
       submission.edit(submission={'posted_grade': scores[i]})

There are cleaner ways to do this but I tried to modify your code as minimally as possible.

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