让我说我有一本字典:
students = {"adrian":["a","b","c","d"], "jamie":["b","b","a","d"], "adam":["a","c","d","d"]}
列表:
answers=["a","b","c","d"]
我只想检查每个元素匹配来自其给定索引的答案与字典中的值。总之,将每个列表与答案进行比较。 然后我会打印学生正确的次数。
例如,如果我将关键字“adrian”的值与我得到的答案进行比较4.如果我将Jamie与答案进行比较,我会得到2.如果我将adam与答案进行比较,我会得到2.
我如何比较两者?
非常感谢您的帮助!
答案 0 :(得分:3)
>>> students = {"adrian":["a","b","c","d"], "jamie":["b","b","a","d"], "adam":["a","c","d","d"]}
>>> answers = ["a","b","c","d"]
>>> {s:sum(t == a for t, a in zip(students[s], answers)) for s in students}
{'jamie': 2, 'adam': 2, 'adrian': 4}
这对每个学生zip
的答案都有答案,然后对它们进行比较,然后总结得出的布尔人。
答案 1 :(得分:1)
import pandas as pd
students = {"adrian":["a","b","c","d"], "jamie":["b","b","a","d"], "adam":["a","c","d","d"]}
answers=["a","b","c","d"]
df = pd.DataFrame(students)
df.apply(lambda x: x==answers).sum()
有点解释:
df.apply(lambda x: x==answers)
将比较每个学生的答案,得到以下数组:
adam adrian jamie
0 True True False
1 False True True
2 False True False
3 True True True
.sum()将执行逐列求和(将True转换为1,将False转换为0),将数组缩减为:
adam 2
adrian 4
jamie 2
答案 2 :(得分:1)
这样的事情?
def get_correct_answers_count(given_answers,
correct_answers):
return sum(1
for student_answer, correct_answer in zip(given_answers,
correct_answers)
if student_answer == correct_answer)
students_correct_answers_count = {
student_name: get_correct_answers_count(given_answers=student_answers,
correct_answers=answers)
for student_name, student_answers in students.items()}
给我们
{'adrian':4,'jamie':2,'adam':2}
答案 3 :(得分:0)
您可以使用zip()获取值和答案的组合
for k,v in students.items():
ans = 0
for i, j in zip(v,answers):
if i==j:
ans+=1
print ans
答案 4 :(得分:0)
我认为这有效
students = {"adrian":["a","b","c","d"],
"jamie":["b","b","a","d"],
"adam":["a","c","d","d"]}
answers = ["a","b","c","d"]
results = {}
for k,v in students.items():
results [k] = 0
for i,answer in enumerate(v):
if answers[i] == v[i]:
results[k]+=1
print (results)
{' adrian':4,' adam':2,' jamie':2}
答案 5 :(得分:0)
基于 set()
的解决方案实施例
data = {'jamie': ['a', 'b', 'c', 'd']}
answers = ['b', 'd', 'c', 'd']
tuples = map(set, zip(data['jamie'], answers))
reduce(lambda y, coll: (len(coll) - 1) + y , tuples, 0)
Out[8]: 2
该示例使用的是数据类型集只能包含唯一的事实。因此,通过压缩两个列表jamie和答案我得到元组。如果元组包含两个相同的元组set()
将使其唯一。
当我减少元组列表时,我使用的事实是,如果集合中有多个元素,则表示错误的答案&算上它。