简体   繁体   English

Python/Pandas - For 循环只记录最终迭代

[英]Python/Pandas - For loop only recording final iteration

Obligatory warning - new to Python and Pandas.强制性警告 - Python 和 Pandas 的新手。

I'm having some difficulty executing a for loop that only returns the last value in the list.我在执行只返回列表中最后一个值的 for 循环时遇到了一些困难。

I have a .csv file containing information that I'd like to run through CanvasAPI to post user scores.我有一个 .csv 文件,其中包含我想通过CanvasAPI运行以发布用户分数的信息。 The .csv layout is: .csv 布局是:

     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).循环成功运行,但实际上只有 .csv 的最后一行被评分(对于 Name_5)。 What am I missing?我错过了什么? Any help greatly appreciated.非常感谢任何帮助。

The issue is in the last for loop.问题出在最后一个 for 循环中。

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

Each time the loop iterates, scorelist[x] will be the latest value of x.每次循环迭代时, scorelist[x] 将是 x 的最新值。 So at the end of the execution, scorelist[x] will be the last value of x.所以在执行结束时, scorelist[x] 将是 x 的最后一个值。

You'll need to save the value of scorelist[x] each time the loop iterates.每次循环迭代时,您都需要保存 scorelist[x] 的值。 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.有更简洁的方法可以做到这一点,但我尝试尽可能少地修改您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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