如何在列表中修改特定元素(取决于另一个字典),其中列表是字典的值? (Python)
给定2个词典:
- 学生的ID和每个问题上有多少要点:
user_probstat_dict = {'106095014': [3, 1, 1], '106095029': [3, 1, 0], '106095033': [3, 1, 0]}
- 学生的ID和他们被欺骗的问题的数量:
user_cheatprob_dict = {'106095029': [1, 3], '106095033': [3]}
我的目的是将分数更改为0被骗了,例如对于ID“ 106095029”,该学生的原始分数:
'106095029': [3, 1, 0]
应该更改为:
'106095029': [0, 1, 0]
由于并非所有学生都被骗了,因此user_cheatprob_dict
不总是包括所有学生IDS。
这是我的代码:
for u, c in user_cheatprob_dict.items():
for ci in c:
prob_ind = ci - 1
user_probstat_dict.update({u:???})
我的想法是首先循环浏览user_cheatprob_dict
,如果有一个学生欺骗了问题,请使用键(Student id = u
)并使用更新函数将值替换为0。
???
在我的代码中是我不知道如何仅参考特定值的部分(通过索引prob_ind )。 我只知道,如果我想更改整个值,我只需要将0放置在
???
零件上即可。
谢谢!
Given 2 dictionaries of:
- the students' id and how many points they've got on each problem:
user_probstat_dict = {'106095014': [3, 1, 1], '106095029': [3, 1, 0], '106095033': [3, 1, 0]}
- the students' id and the number of problem that they've been cheated:
user_cheatprob_dict = {'106095029': [1, 3], '106095033': [3]}
My aim is to change the score into 0 for those problems that have been cheated, like for the id '106095029', this student's original score:
'106095029': [3, 1, 0]
should be changed into:
'106095029': [0, 1, 0]
Since maybe not all of the students have cheated, the user_cheatprob_dict
won't always include all of the student ids.
Here's my code:
for u, c in user_cheatprob_dict.items():
for ci in c:
prob_ind = ci - 1
user_probstat_dict.update({u:???})
My thought is to first loop over the user_cheatprob_dict
, if there's a student that has problems cheated, then take the key (student id = u
) and use the update function to replace the value into 0.
The ???
in my code is the part where I don't know how to refer to only the specific value(by the index prob_ind
)in the list.
I only knew that if I want to change the whole value, I just need to place 0 at the ???
part.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我有2种解决方案,具体取决于您的需求。另外,这些解决方案是安全的:如果一个或另一个或另一个学生缺少学生的ID,或者被骗的问题的编号与任何问题不符,则不会提出。
1。重新计算您的解决方案
这是更紧凑的,但是由于它重新创建了新的词典,因此它会消耗更多的内存。仅在小样品上使用它。优势在于,您的输入不变。
2。直接在输入中替换
不太紧凑,但记忆消耗也少。并且您的输入已更改!
I have 2 solutions, depending on your needs. Also, those solutions are safe: it won't raise if a student's id is missing in one or another dict, or if a cheated problem's number doesn't correspond to any problem.
1. Recompute your solution
This is the more compact one, but it consumes more memory since it recreates a new dictionary. Use it only on small enough samples. The advantage is that you let your input unchanged.
2. Replace directly in the input
Less compact, but also less memory consumption. And your input is changed!
您可以使用以下方式使用字典遍历:
输出: 请注意,User_cheatprob_dict的索引被-1取代以获取正确的问题索引
You can use dictionary traversal as follows:
Output: Note that the index of user_cheatprob_dict is offset by -1 to get the correct problem index