【问题标题】:Appending a key:value from one dictionary to another [closed]将键:值从一个字典附加到另一个 [关闭]
【发布时间】:2021-03-04 09:39:48
【问题描述】:

所以我希望能够使用词典制作多项选择测验程序。我有一本字典,其中所有问题为键,答案为值,第二本字典为空。我想将某人可能遇到的所有不正确的问题附加到空字典中。我想这样做是为了允许用户重新参加考试,但仅限于他们回答错误的问题。然而,我无法找到一种方法来将一个列表中的键和值附加到另一个列表中而不是具体的。

下面是我的代码:

def intro():    
    print("Hello and welcome to the random questions test")
    global name   
    name = input("what is your name? " + "\n" + "\n")
    if name == "":
        print("Enter a valid name!")
        name = input("what is your name? " + "\n" + "\n")
    else:
        ans2 = input("\n" + "Hello " + name + " Are you sure you want to take the exam? (yes/no)"  + "\n" + "\n")
        if ans2 == "no":
            print("\n" + "aw man, until next time " + name + "!" + "\n")   
        elif ans2 == "yes":
            print("\n" + "Okay!" + "\n")
            Quiz()

def Quiz():
    q1 = """Who holds the NFL record for the most receiving yards in a single game?
        a.  Calvin Johnson
        b.  Deandre Hopkins
        c.  Flipper Anderson
        d.  Jerry Rice"""
    q2 = """In what year was the eiffel tower built?
        a.  1492
        b.  1889
        c.  2013
        d.  1766"""
    q3 = """How many countries are in the world today?
        a.  205
        b.  195
        c.  673
        d.  142"""
    q4 = """Who is the CEO of apple currently (2020)?
        a.  Tim Cook
        b.  Sergio Kitchens
        c.  Daniel Johnson
        d.  Steve Jobs"""
    q5 = """who is the 23rd president of the united states?
        a.  Grover Cleveland 
        b.  Andrew Jackson
        c.  Anderson Berkshire
        d.  Benjamin Harrison"""
    q6 = """X + 5x - 10 = 500... What does X equal?
        a.  85
        b.  84
        c.  102
        d.  0"""
    q7 = """Who is currently the richest person on earth?
        a.  Tim Cook
        b.  Jeff Bezos
        c.  Bill Gates
        d.  Bill Nye"""
    q8 = """When was Howard University Established?
        a.  May 4, 2002
        b.  March 5, 1855
        c.  September 1, 1844
        d.  March 2, 1867"""
    q9 = """What can you catch but not throw?
        a.  A football
        b.  A conversation
        c.  A cold
        d.  A tennis ball in the Appalachian Mountains"""
    q10 = """Which country is responsible for the production of 95% of the worlds opal stones?
        a.  Brazil 
        b.  Mexico
        c.  Honduras
        d.  Austrailia"""
    q11 = """How many species of Toothed and Baleen whales exist?
        a.  14 and 2
        b.  76 and 14
        c.  5 and 10
        d.  75,000"""
    q12 = """Who holds the world record for the most chicken nuggets eaten in 1 hour?
        a.  Naader Reda
        b.  Nicolo Reda
        c.  Stefano Neder
        d.  Josh Jacobs"""
    q13 = """Who invented the bessemer process?
        a.  Henry Bessemer 
        b.  Markus Bessemer
        c.  Bessemer Robinson
        d.  Anakin Skywalker"""
    q14 = """When was Mortal Kombat 6 released?
        a.  April 1, 2002
        b.  August 15, 2007
        c.  October 4, 2004
        d.  December 25, 2006"""
    q15 = """In which City located in the USA is it illegal to say "Oh, boy"?
        a.  Denver, Colorado  
        b.  Lexington, Kentucky
        c.  Jonesboro, Georgia
        d.  Wilbur, Washington"""
    Questions = {q1: 'c', q2: 'b', q3: 'b', q4: 'a', q5: 'd', q6: 'a', q7: 'b', q8: 'd', q9: 'c', q10: 'd', q11: 'b', q12: 'a', q13: 'a', q14: 'c', q15: 'c' }
    inc_questions = {}
    score = 0
    for q in Questions:
        print(q)
        ans = input("> ")
        if ans.lower() == Questions[q]:
            print("\n" + "Correct!" + "\n")
            score += 1
        else:
            print("\n" + "Incorrect!" + "\n")
            for q, a in Questions.items():
                if ans.lower() != Questions[q]:
                    inc_questions[q] = a 
   
    if score == 15: 
        print("Congratulations " + name + ", you scored a perfect 15/15!")
    elif score < 15 and score > 11:
        print("Good job " + name + "! you got " + str(score) + " out of 15 correct!")
        print("\n" + "Would you like to re-answer the questions that were incorrect?" + "\n")
    elif score < 12 and score > 8:
        print("You did pretty well " + name + ", you got " + str(score) + " out of 15 correct!")
        print("\n" + "Would you like to re-answer the questions that were incorrect?" + "\n")
    elif score < 9 and score > 5:
        print("Unfortunately " + name + " you did not pass, you got " + str(score) + " out of 15 correct!")
        print("\n" + "Would you like to re-answer the questions that were incorrect?" + "\n")
    elif score < 6 and score > 0:
        print("Jeez " + name + " you did awful lol, you got " + str(score) + " out of 15 correct!")
        print("\n" + "Would you like to re-answer the questions that were incorrect?" + "\n")
    elif score == 0:
        print("Oh lord " + name +" you need some serious help you got nothing right!")
        print("\n" + "Would you like a retake?" + "\n")
    print(inc_questions)

intro()

【问题讨论】:

  • 我想我会用键(“q1”,“q2”,......“q15”)重新定义您的初始字典,然后字典值可以是一个元组(“问题文本”,“正确答案值”。您可以根据键、值对在字典中循环。然后用 dict[key][0] 提出问题并比较 dict[kay][1] 的答案。如果答案正确,请更新答案计数,如果答案不正确,将问题键存储在重新测验列表中,因此只有答案不正确的问题才会被重新提出。
  • 字典是一个键->值对,根据定义。如果你想追加你可能会更好用一个列表。如果您真的希望能够“附加”stackoverflow.com/questions/10058140/… ...,您也可以使用有序的字典。但是,我仍然不明白您为什么要“附加”到字典 - 列表和字典都是可迭代。
  • 欢迎来到 SO!查看tour。这是太多的代码。请发送minimal reproducible example。你可以edit这个问题。如果您想了解更多提示,请查看How to Ask
  • 根据我的回答,问题标题不匹配。我远离键值对,而是使用列表中的元组来使其正常工作。这更像是一个列表解决方案,而不是一个 dict 解决方案。 list vs. dict 的原因是跟踪未回答的问题并快速遍历它们。

标签: python python-3.x


【解决方案1】:

有趣的问题要解决。查看此代码,看看它是否为您提供了继续进行测验的可重复过程。我有一点问题的唯一领域是你的大 if 语句检查分数并打印不同的响应。当用户的问题较少时,我不得不将较早回答的问题添加到计数中以保持在相同的范围内。否则,这应该可以工作。

我改变的东西。

#1:问题是一个元组列表。每个元组都是一个问答(q1,'c')作为例子。

#2:由于我们需要重复问题,我每次都在遍历错误的问题列表。首先,我将所有问题都设置为不正确。所以不正确的问题列表的值是 0 到 14。

#3:每次用户正确回答时,我都会从错误的问题列表中删除问题。

#4:由于我通过删除正确回答的问题来操纵列表本身,因此我不能使用 for 循环。相反,我使用了一个while循环并确保我只遍历列表直到列表的最大值

#5:我正在循环测验功能,直到用户决定停止播放。首先,我将标志设置为yes 并在调用 Quiz 函数之前对其进行检查。我将用户的决定作为退货声明退回。这有助于循环继续进行。

#6:最后,我把所有的问题都移到了外面,并把Questions 变成了一个全局变量。由于我们要调用 Quiz 几次,我不希望每次都定义 Questions。如果你想把它藏在里面,那是你的选择。它不会影响整体解决方案。但是,您需要将其设为元组列表。此外,inc_questions 必须是全局的,因此您可以根据需要多次操作它。

下面是代码。如果您发现任何错误,请告诉我。

def intro():    
    print("Hello and welcome to the random questions test")
    global name   
    name = input("what is your name? " + "\n" + "\n")
    if name == "":
        print("Enter a valid name!")
        name = input("what is your name? " + "\n" + "\n")
    else:
        ans2 = input("\n" + "Hello " + name + " Are you sure you want to take the exam? (yes/no)"  + "\n" + "\n")
        if ans2.lower() == "no":
            print("\n" + "aw man, until next time " + name + "!" + "\n")   
        elif ans2.lower() == "yes":
            print("\n" + "Okay!" + "\n")
            ans3 = 'yes'
            while ans3.lower() == 'yes':
                ans3 = Quiz()

def Quiz():
    score = 15 - len(inc_questions)
    i = 0
    while i < len(inc_questions):
        x = inc_questions[i]
        print(Questions[x][0])
        ans = input("> ")
        if ans.lower() == Questions[x][1]:
            print("\n" + "Correct!" + "\n")
            score += 1
            inc_questions.pop(i)
        else:
            print("\n" + "Incorrect!" + "\n")
            i +=1
   
    if score == 15: 
        print("Congratulations " + name + ", you scored a perfect 15/15!")
    elif score < 15 and score > 11:
        print("Good job " + name + "! you got " + str(score) + " out of 15 correct!")
    elif score < 12 and score > 8:
        print("You did pretty well " + name + ", you got " + str(score) + " out of 15 correct!")
    elif score < 9 and score > 5:
        print("Unfortunately " + name + " you did not pass, you got " + str(score) + " out of 15 correct!")
    elif score < 6 and score > 0:
        print("Jeez " + name + " you did awful lol, you got " + str(score) + " out of 15 correct!")
    elif score == 0:
        print("Oh lord " + name +" you need some serious help you got nothing right!")

    if score == 0:
        print("\n" + "Would you like a retake?" + "\n")
        ans1 = input("> ")
    elif score < 15:
        print("\n" + "Would you like to retake the questions that were incorrect?" + "\n")
        ans1 = input("> ")
    else: ans1 = ''
    
    return ans1

q1 = """Who holds the NFL record for the most receiving yards in a single game?
        a.  Calvin Johnson
        b.  Deandre Hopkins
        c.  Flipper Anderson
        d.  Jerry Rice"""
q2 = """In what year was the eiffel tower built?
        a.  1492
        b.  1889
        c.  2013
        d.  1766"""
q3 = """How many countries are in the world today?
        a.  205
        b.  195
        c.  673
        d.  142"""
q4 = """Who is the CEO of apple currently (2020)?
        a.  Tim Cook
        b.  Sergio Kitchens
        c.  Daniel Johnson
        d.  Steve Jobs"""
q5 = """who is the 23rd president of the united states?
        a.  Grover Cleveland 
        b.  Andrew Jackson
        c.  Anderson Berkshire
        d.  Benjamin Harrison"""
q6 = """X + 5x - 10 = 500... What does X equal?
        a.  85
        b.  84
        c.  102
        d.  0"""
q7 = """Who is currently the richest person on earth?
        a.  Tim Cook
        b.  Jeff Bezos
        c.  Bill Gates
        d.  Bill Nye"""
q8 = """When was Howard University Established?
        a.  May 4, 2002
        b.  March 5, 1855
        c.  September 1, 1844
        d.  March 2, 1867"""
q9 = """What can you catch but not throw?
        a.  A football
        b.  A conversation
        c.  A cold
        d.  A tennis ball in the Appalachian Mountains"""
q10 = """Which country is responsible for the production of 95% of the worlds opal stones?
        a.  Brazil 
        b.  Mexico
        c.  Honduras
        d.  Austrailia"""
q11 = """How many species of Toothed and Baleen whales exist?
        a.  14 and 2
        b.  76 and 14
        c.  5 and 10
        d.  75,000"""
q12 = """Who holds the world record for the most chicken nuggets eaten in 1 hour?
        a.  Naader Reda
        b.  Nicolo Reda
        c.  Stefano Neder
        d.  Josh Jacobs"""
q13 = """Who invented the bessemer process?
        a.  Henry Bessemer 
        b.  Markus Bessemer
        c.  Bessemer Robinson
        d.  Anakin Skywalker"""
q14 = """When was Mortal Kombat 6 released?
        a.  April 1, 2002
        b.  August 15, 2007
        c.  October 4, 2004
        d.  December 25, 2006"""
q15 = """In which City located in the USA is it illegal to say "Oh, boy"?
        a.  Denver, Colorado  
        b.  Lexington, Kentucky
        c.  Jonesboro, Georgia
        d.  Wilbur, Washington"""

Questions = [(q1,'c'),  (q2,'b'),  (q3,'b'), (q4,'a'),  (q5,'d'),  (q6,'a'),
             (q7,'b'),  (q8,'d'),  (q9,'c'), (q10,'d'), (q11,'b'), (q12,'a'),
             (q13,'a'), (q14,'c'), (q15,'c')]

inc_questions = [i for i in range(15)]

intro()

这是再次回到问题的输出部分。

以下问题我答错了:[0, 3, 4, 6, 7, 9, 11, 12, 13, 14]的索引值

这是第 15 个问题。然后它去问第一个和第四个问题。

In which City located in the USA is it illegal to say "Oh, boy"?
        a.  Denver, Colorado  
        b.  Lexington, Kentucky
        c.  Jonesboro, Georgia
        d.  Wilbur, Washington
> a

Incorrect!

Jeez Joe you did awful lol, you got 5 out of 15 correct!

Would you like to retake the questions that were incorrect?

> yes
Who holds the NFL record for the most receiving yards in a single game?
        a.  Calvin Johnson
        b.  Deandre Hopkins
        c.  Flipper Anderson
        d.  Jerry Rice
> a

Incorrect!

Who is the CEO of apple currently (2020)?
        a.  Tim Cook
        b.  Sergio Kitchens
        c.  Daniel Johnson
        d.  Steve Jobs
> a

Correct!

who is the 23rd president of the united states?
        a.  Grover Cleveland 
        b.  Andrew Jackson
        c.  Anderson Berkshire
        d.  Benjamin Harrison
> a

Incorrect!

Who is currently the richest person on earth?
        a.  Tim Cook
        b.  Jeff Bezos
        c.  Bill Gates
        d.  Bill Nye
> 

然后它返回并再次询问。从上一轮来看,我的第 15 题是不正确的。所以它又问了最后一个问题。

When was Mortal Kombat 6 released?
        a.  April 1, 2002
        b.  August 15, 2007
        c.  October 4, 2004
        d.  December 25, 2006
> c

Correct!

In which City located in the USA is it illegal to say "Oh, boy"?
        a.  Denver, Colorado  
        b.  Lexington, Kentucky
        c.  Jonesboro, Georgia
        d.  Wilbur, Washington
> b

Incorrect!

You did pretty well Joe, you got 10 out of 15 correct!

Would you like to retake the questions that were incorrect?

> no
>>> 

我又错过了这些问题 [0, 4, 7, 12, 14]。这一次,我说no,程序就结束了。

【讨论】:

  • 修复了小改动。更新的代码有效。请使用此版本。
  • 如果这解决了你的问题,别忘了点赞。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-06-19
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-10
  • 1970-01-01
相关资源
最近更新 更多