【问题标题】:How do i compare the the user response with actual answer that are stored- python我如何将用户响应与存储的实际答案进行比较-python
【发布时间】:2013-12-24 18:11:49
【问题描述】:

此 for 循环将让用户使用单选按钮中的值进行多次响应,其值也类似 1、3、5、2、1....

for i in range(1, 10):
    resp_i = form.getvalue('opt_%d' %i, '0')
    resp[i] = resp_i
    print resp[i] 

output of this loop: 3 4 1 2 1 0 0 0 0

此代码包含存储在数据库中的实际答案,其值也类似 1,2, 3 ,5, 2.......row[0] 包含问题 ID,row[1] 包含答案

for row in prsnobj.result:
    ansdb = {row[0] : row[1]}
    print ansdb

output:  {1L: 3L} {2L: 4L} {3L: 2L} {4L: 2L} {5L: 2L} 

现在我的问题是我想将用户响应与存储在数据库中的实际答案进行比较。?我要这样做吗?

我试过的代码……不可行

res1= int(form.getvalue('opt_1', '0'))
res2 = int(form.getvalue('opt_2', '0'))
res3 = int(form.getvalue('opt_3', '0'))
res4 = int(form.getvalue('opt_4', '0'))
res5 = int(form.getvalue('opt_5', '0'))

actual_ans_dict = {}
count = 0
b = []
for data in prsnobj.result:
    actual_ans_dict[data[0]] = data[1]

if res1 == actual_ans_dict[1]:
    count += 1
if res2 == actual_ans_dict[2]:
    count += 1
if res3 == actual_ans_dict[3]:
    count += 1
if res4 == actual_ans_dict[4]:
    count += 1
if res5 == actual_ans_dict[5]:
    count += 1

if count:
    b.append(count)

if len(b)==0:
    print "Fail"

else:
   for each in b:
       print "<b>Score: ", each

【问题讨论】:

  • 行[0] id 是什么样的?如果他们只是简单地编号(1,2,3,4)以匹配问题编号,这将很容易
  • row[0] 只是像 1,2,3,4,5 这样的数字......
  • 不喜欢这篇文章的人,请说出你不喜欢这篇文章的原因,这样提问者就会知道他的提问有什么问题。
  • @Andy 我猜是因为提问者似乎没有尝试为自己解决问题,只是要求有人去做。
  • 展示你尝试过的东西是值得的,而且你被否决的可能性更小..

标签: python if-statement for-loop dictionary


【解决方案1】:

假设您实际上有一个dict 的问题要回答,

for index, answer in enumerate(xrange(len(resp))):
    if answer == ansbd[index + 1]:
        print "Correct"
    else:
        print "Incorrect!"

这是Enumerate 的文档。如果我正确理解了你的问题。列表resp 的槽对应于问题编号,也就是dictansbd 中的键。因此,我们遍历list 并针对每个条目,查看它是否与ansbd 中的coorespond 答案相匹配。

【讨论】:

  • 表示key不在map中。如果1,2,... 存储为映射中的键,这将起作用。
  • @user3003685 打印出地图中的键以查看它们的确切含义。 for key in yourDict.keys(): print key。如果他们不是您在评论中所说的1,2,3,...,这就是此方法不起作用的原因。
  • 1,2,3,4,5 是我地图上的眼睛..我检查了
  • @user3003685 你确定它们不是字符串吗?如果是这样,这将不起作用,您必须执行str(index+1)。如果不是,我向您保证,如果 resp, n 的长度与问题数 [1,n] 匹配,这将起作用。
  • 是的,它们不是字符串...我在数据库名称 QId 中有一个列...它是自动递增的...因此它是一个整数
【解决方案2】:
for i in range(1, len(resp)+1):     # assuming like you said, your question id's and answers are both integers
    if  resp[i] == ansdb[i]: # this assumes your question id's start at 1
        print "Right!" 
    else:
        print "Wrong.."

if resp = {1: 2, 2: 9, 3: 2, 4: 8, 5: 3, 6: 5}
and ansdb = {1: 2, 2: 4, 3: 6, 4: 8, 5: 3, 6: 5}

result is:

right
wrong
wrong
right
right
right

which it should be

【讨论】:

  • 这也假设 resp 是一个列表。这个问题需要大量澄清
  • @Totem 它显然有效,不过,感谢您向他展示。有些东西不是 OP 所说/认为的......
  • 好的,好吧,如果 resp 是一个 dict 并且 ansdb 是一个 dict.. 并且两者都使用表示问题编号的整数作为键,而将答案作为值,那么这可行...
猜你喜欢
  • 1970-01-01
  • 2015-05-05
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多