使用用户输入在Python中创建词典

2024-05-21 00:13:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始学习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

我做这件事有困难,所以任何帮助都是非常感谢的。


Tags: 用户name程序getreturn字典testsstudent
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...]称为“列表理解”。它们遍历字符串编号列表,使其成为整数(使用int())。

也许你应该创建一个简单的类?

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”]而不是name etc,其中d是字典对象)

相关问题 更多 >