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)
例如,根据用户输入,我正在尝试将记录打印出来,如下所示,并尝试将所有测试值保存在指定的名称下。
{'name' : ' sam', 'test': '99','98','78'}
{'name' : 'john', 'test': '92','68','70'}
或
{'sam': '99','98','78'}
{'john':'92','68','70'}
答案 0 :(得分:0)
使用list
作为标记暗示:
record['test'] = []
for test in range(tests):
score = input('Please enter test score: ')
record['test'].append(score)
答案 1 :(得分:0)
您应该为每个字典关键项保留list值,其中键将是学生姓名,list
将包含测试分数。请参阅下面的示例。
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)
输出:
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']}
答案 2 :(得分:0)
我在这里看到一些问题:
record
参数会立即被该方法覆盖,这可能导致路上的陌生感我的建议:
为Student
创建一个类,并在那里提供所有信息。
class Student(object):
def __init__(self, name):
self.name = name
self.test_scores = []
我建议您定义a suitable __str__()
值,但我将此作为练习留给读者。
在某处创建一个记录列表,它只是一个学生列表。
students = []
调整您的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)
答案 3 :(得分:0)
如果您愿意,可以继续使用字典:
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)
这将记录:
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'}
或者您可以使用以下方式进行:
for name in range(students):
record[input('Please enter students name: ')] = input('Please enter test score: ')
print (record)
这将首先询问您的测试成绩,然后是名称。