我最近开始学习Python,并且正忙着通过Codecademy教程。我刚刚完成了教程,您可以在其中创建一个程序来确定字典中标记的平均值。下面是当前的代码:
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
class_list = [lloyd, alice, tyler]
def average(numbers):
total = sum(numbers)
total = float(total)
total = total / len(numbers)
return total
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return homework * 0.1 + quizzes * 0.3 + tests * 0.6
def get_class_average(students):
results = []
for student in students:
results.append(get_average(student))
return average(results)
print get_class_average(class_list
但我想做的扩展是通过让程序要求用户在第一行输入lloyd
以及输入字典中的所有值,使其更加用户友好。此外,我希望每次用户输入字典名称(例如第一行的lloyd
)时,程序都会生成一个新字典。然后用class_list
填写所有词典。最后我想做到这一点,用户也可以在行中输入标记的权重:
return homework * 0.1 + quizzes * 0.3 + tests * 0.6
我很难做到这一点,所以任何帮助都会受到高度赞赏。
答案 0 :(得分:2)
您无法生成动态变量名称,但无论如何都不需要。只需使用while输入,然后添加到列表
cancel = False
class_list = []
while (True):
name = input("Give the name of the user you want to add: ")
homework = [int(i) for i in input("Homework marks (seperated by spaces): ").split(" ")]
quizzes = [int(i) for i in input("Quiz marks (seperated by spaces): ").split(" ")]
tests = [int(i) for i in input("Test marks (seperated by spaces): ").split(" ")]
class_list.append({
"name": name,
"homework": homework,
"quizzes": quizzes,
"tests": tests
})
cont = input("Want to add another? (Y/N)")
if cont == "N":
break;
print(class_list)
[int(i) for i in...]
被称为"列表理解。它们遍历字符串编号列表,使它们成为INtegers(使用int())。
答案 1 :(得分:-2)
也许你应该创建一个简单的类?
class Student:
def __init__(self, name, homework, quizzes, tests):
self.name = name
self.homework = homework
self.quizzes = quizzes
self.tests = tests
并使用这样的函数输入:
def input_student():
name = input("Enter name")
homework = [float(h) for h in input("Enter homework results separated by a space:)]
# same for quizzes and tests
class_list.append(Student(name, homework, quizzes, tests))
如果你不想创建一个类,你可以用字典做同样的事情(分配给d [“name”]而不是名字等,其中d是你的字典对象)