简体   繁体   English

如何在不互相替换的情况下获得字典的多个值?

[英]How can I get multiple values for my dictionary without them replacing each other?

def newRecord(record):
    record= {'name' : 'test'}
    students = int(input('How many students are in your class? '))
    tests = int(input('How many tests have you given? '))
    for name in range(students):
        record ['name'] = input('Please enter students name: ')
        for test in range(tests):
            record ['test'] = input('Please enter test score: ')
    print (record)

For example, depending on the user input, I am trying to get record to print out as shown below and also trying to get all the values for test to be saved under the names specified. 例如,根据用户的输入,我试图获取记录以进行打印,如下所示,并且试图将所有要测试的值保存在指定的名称下。

{'name' : ' sam', 'test':  '99','98','78'}
{'name' : 'john', 'test':  '92','68','70'}

or 要么

{'sam': '99','98','78'}
{'john':'92','68','70'}

use list as your tags imply: 使用list因为您的标签暗示:

record['test'] = []
for test in range(tests):
    score = input('Please enter test score: ')
    record['test'].append(score)

You should keep a list as values for each of the dictionary key items where keys will be student names and list will contain the test scores. 您应该保留一个列表作为每个词典关键字项的值,其中关键字将是学生姓名,而list将包含测试成绩。 See an example below. 请参阅下面的示例。

record= {}
students = int(input('How many students are in your class? '))
tests = int(input('How many tests have you given? '))
for name in range(students):
    name = input('Please enter students name: ')
    testScores = []
    for test in range(tests):
        testScores.append(input('Please enter test score: '))
    record[name] = testScores
print (record)

It outputs: 它输出:

How many students are in your class? 2
How many tests have you given? 3
Please enter students name: Alex
Please enter test score: 80
Please enter test score: 75
Please enter test score: 95
Please enter students name: Mac
Please enter test score: 90
Please enter test score: 88
Please enter test score: 79
{'Alex': ['80', '75', '95'], 'Mac': ['90', '88', '79']}

I see a few problems here: 我在这里看到一些问题:

  • Your record parameter is instantly overwritten by the method, which may lead to strangeness down the road 该方法会立即覆盖您的record参数,这可能会导致一路奇怪
  • You're attempting to encapsulate multiple values in a data structure which only handles key-value relationships 您试图将多个值封装在仅处理键值关系的数据结构中
  • You're not really taking advantage of a useful design element with Python - class abstraction . 您并没有真正利用Python 类抽象的有用设计元素。

My recommendations: 我的建议:

  1. Create a class for Student s and have all of their information referencable in there. Student创建一个类,并在其中引用所有信息。

     class Student(object): def __init__(self, name): self.name = name self.test_scores = [] 

    Here I'd recommend you define a suitable __str__() value, but I leave this as an exercise for the reader. 在这里,我建议您定义一个合适的__str__()值,但我将其留给读者练习。

  2. Create a list of records somewhere which is simply a list of students. 在某个地方创建一个记录列表,它只是一个学生列表。

     students = [] 
  3. Adjust your newRecord method to make use of the class (and rename it to better describe its purpose). 调整newRecord方法以利用该类(并将其重命名以更好地描述其目的)。

     def create_new_records(): students = int(input('How many students are in your class? ')) tests = int(input('How many tests have you given? ')) for i in range(students): student_name = input('Please enter students name: ') student = Student(student_name) for j in range(tests): student.test_scores.append(input('Please enter test score: ')) students.append(student) print(student) 

You can keep using a dictionary if you'd like: 您可以根据需要继续使用字典:

def newRecord():
    record = {}
    students = int(input('How many students are in your class? '))
    for name in range(students):
        name = input('Please enter students name: ')
        test = input('Please enter test score: ')
        record[name] = test
    print(record)

This will log: 这将记录:

How many students are in your class? 3
Please enter students name: john
Please enter test score: 12
Please enter students name: mike
Please enter test score: 33, 45, 66
Please enter students name: otherjohn
Please enter test score: 9
{'john': '12', 'otherjohn': '9', 'mike': '33, 45, 66'}

Or you can do it in-place with: 或者,您可以使用以下方法就地进行:

for name in range(students):
    record[input('Please enter students name: ')] = input('Please enter test score: ')
print (record)

This will ask you for the test scores first though and then the name. 但是,这将首先要求您提供测试成绩,然后是名称。

暂无
暂无

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

相关问题 Python - 如何在不互相干扰的情况下多次播放相同的声音? - Python - How can I play the same sound multiple times without them interrupting each other? 如何打印多行,然后让后续行分别替换每行(Python) - How can I print multiple lines, having subsequent lines replacing each of them independently (Python) 如何获得字典中每个键的值长度? - How can I get lengths of values for each of the key in a dictionary? 如何在不将它们相互合并的情况下检测此图像中具有白色背景的所有对象? - How can I detect all objects in this image with a white background without merging them with each other? 如何在不使用 sum() 的情况下从每个键中有多个值的字典中的平均值计算平均值? - How do I calculate an average from averages in a dictionary with multiple values in each key without using sum()? 我如何从 2 个列表中获取值并将它们放入 python 中的字典中 - How can i get values from 2 lists and put them into a dictionary in python 如何自动调整散点图标签,而不会被python中的其他标签覆盖? - How can I auto-adjust my scatterplot labels without them being overlapped by other labels in python? 如何在字典中存储值 - How can i store values in my dictionary 如何使用 `return` 从 for 循环中取回多个值? 我可以把它们放在一个列表中吗? - How can I use `return` to get back multiple values from a for loop? Can I put them in a list? 这是 {'': [ {}, {}, {} ]} Dictionary of List of a Dictionary 吗? 如何拆分内部值以便单独打印/处理它们? - Is this {'': [ {}, {}, {} ]} Dictionary of List of a Dictionary? How can I Split the inside values so I can print/process them separately?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM