简体   繁体   English

如何检测字典中是否存在值?

[英]How to detect if a value exists in a dictionary?

Here I have code that gives students a math quiz and saves their scores in a text file. 在这里,我有一些代码,可以给学生一个数学测验,并将他们的分数保存在一个文本文件中。 Now I'm trying to add to my code to enable it to save the student's last three scores to their name. 现在,我试图添加到我的代码中,以使其能够将学生的最后三个分数保存到他们的名字中。 To do this I know I will have to use 2D arrays, but I'm struggling to add an if statement to my code that essentially says "If name is in dictionary, save score to name". 为此,我知道我将不得不使用2D数组,但是我正在努力在代码中添加一条if语句,该语句本质上说“如果名称在字典中,则将分数保存到名称中”。 How would I do this? 我该怎么做?

Here is my code: 这是我的代码:

import random
import sys

def get_input_or_quit(prompt, quit="Q"):
    prompt += " (Press '{}' to exit) : ".format(quit)
    val = input(prompt).strip()
    if val.upper() == quit:
        sys.exit("Goodbye")
    return val

def prompt_bool(prompt):
    while True:
        val = get_input_or_quit(prompt).lower()
        if val == 'yes':
          return True
        elif val == 'no':
          return False
        else:
         print ("Invalid input '{}', please try again".format(val))


def prompt_int_small(prompt='', choices=(1,2)):
    while True:
        val = get_input_or_quit(prompt)
        try:
            val = int(val)
            if choices and val not in choices:
                raise ValueError("{} is not in {}".format(val, choices))
            return val
        except (TypeError, ValueError) as e:
                print(
                    "Not a valid number ({}), please try again".format(e)
                    )

def prompt_int_big(prompt='', choices=(1,2,3)):
    while True:
        val = get_input_or_quit(prompt)
        try:
            val = int(val)
            if choices and val not in choices:
                raise ValueError("{} is not in {}".format(val, choices))
            return val
        except (TypeError, ValueError) as e:
                print(
                    "Not a valid number ({}), please try again".format(e)
                    )

role = prompt_int_small("Are you a teacher or student? Press 1 if you are a student or 2 if you are a teacher")
if role == 1:
    score=0
    name=input("What is your name?")
    print ("Alright",name,"welcome to your maths quiz."
            " Remember to round all answers to 5 decimal places.")
    level_of_difficulty = prompt_int_big("What level of difficulty are you working at?\n"
                                 "Press 1 for low, 2 for intermediate "
                                    "or 3 for high\n")


    if level_of_difficulty == 3:
        ops = ['+', '-', '*', '/']
    else:
        ops = ['+', '-', '*']

    for question_num in range(1, 11):
        if level_of_difficulty == 1:
            max_number = 10
        else:
            max_number = 20

        number_1 = random.randrange(1, max_number)
        number_2 = random.randrange(1, max_number)

        operation = random.choice(ops)
        maths = round(eval(str(number_1) + operation + str(number_2)),5)
        print('\nQuestion number: {}'.format(question_num))
        print ("The question is",number_1,operation,number_2)
        answer = float(input("What is your answer: "))
        if answer == maths:
            print("Correct")
            score = score + 1
        else:
            print ("Incorrect. The actual answer is",maths)

    if score >5:
        print("Well done you scored",score,"out of 10")
    else:
        print("Unfortunately you only scored",score,"out of 10. Better luck next time")

    class_number = prompt_int_big("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")

    filename = (str(class_number) + "txt")
    with open(filename, 'a') as f:
        f.write("\n" + str(name) + " scored " + str(score) +  " on difficulty level " + str(level_of_difficulty) + "\n")
    with open(filename) as f:
        lines = [line for line in f if line.strip()]
        lines.sort()

    if prompt_bool("Do you wish to view previous results for your class"):
        for line in lines:
            print (line)
    else:
        sys.exit("Thanks for taking part in the quiz, your teacher should discuss your score with you later")
if role == 2:
    class_number = prompt_int_big("Which class' scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3")
    filename = (str(class_number) + "txt")

    f = open(filename, "r")
    lines = [line for line in f if line.strip()]
    lines.sort()
    for line in lines:
        print (line)

Here is the section where I am trying to add this if statement: 这是我要添加此if语句的部分:

class_number = prompt_int_big("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")

    filename = (str(class_number) + "txt")
    with open(filename, 'a') as f:
        f.write("\n" + str(name) + " scored " + str(score) +  " on difficulty level " + str(level_of_difficulty) + "\n")
    with open(filename) as f:
        lines = [line for line in f if line.strip()]
        lines.sort()

If can simply do 'in' 如果可以简单地做

if 'Name' in Variable:
   do stuff

The variable can be a list or dictionary. 该变量可以是列表或字典。

Since you anyway read the file content back into lines , if your ultimate goal is to show the last three results, I would rather approach it by extracting the information from there inside your prompt_bool("Do you wish to view previous results for your class") section along the lines of: 既然您还是将文件内容读回了几lines ,所以如果您的最终目标是显示最后三个结果,那么我宁愿通过从您的prompt_bool("Do you wish to view previous results for your class")提取信息来prompt_bool("Do you wish to view previous results for your class")部分:

if prompt_bool("Do you wish to view previous results for your class"):
  scores_shown=0
  for line in lines[::-1]:
    if name==line.split(' scored ')[0].strip():
      print(line)
      scores_shown+=1
      if scores_shown>=3:
        break

This would not collocate the scores in the same way as a dictionary would however. 但是,这不会以与字典相同的方式来配置分数。

You could populate a dictionary of lists of scores doing something like this: 您可以填充分数列表的字典,执行以下操作:

if name in d:
  d[name].append(score)
else:
  d[name]=[score]

you could even have a nested list to include the difficulty level eg: d[name]=[[score,level_of_difficulty]] to make the first list item, then d[name].append([score,level_of_difficulty]) for the subsequent items in a dictionary d . 您甚至可以使用嵌套列表来包括难度级别,例如: d[name]=[[score,level_of_difficulty]]来制作第一个列表项,然后是d[name].append([score,level_of_difficulty])作为随后的列表项词典中的项目d

The code would fail if someone has a name which includes the string ' scored ' . 如果有人的名字包含字符串' scored ' ,则该代码将失败。

On a side note, prompt_int_big and prompt_int_small are identical except for the choices tuple. prompt_int_big prompt_int_small ,除了choices元组之外, prompt_int_bigprompt_int_small相同。 To avoid duplicate code I would set one of them as a default prompt_int and when using the other, just add it as an argument, utilizing the flexibility of your code; 为了避免重复的代码,我将其中一个设置为默认的prompt_int而在使用另一个时,只需利用代码的灵活性将其添加为参数即可。 eg. 例如。 prompt_int(choices=(1,2,3)) or prompt_int("my prompt",(1,2,3,4)) . prompt_int(choices=(1,2,3))prompt_int("my prompt",(1,2,3,4)) Also "txt" could be replaced with ".txt" to make it easier for some OS's to understand the file type. 同样, "txt"也可以替换为".txt"以使某些操作系统更容易理解文件类型。

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

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