使用Python设置列表存储30个学生的姓氏以及test1和test2的测试标记,这两个标记都是50个

2024-05-15 20:58:35 发布

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

我正试着帮我儿子(我们都是Python新手)做一些Python作业,他刚刚开始编写代码,看来我也是。问题如下:

设置一维数组/列表以存储以下内容:

30个学生姓

学生考1分-满分50分

学生考试2分-满分50分

每个学生的总分

输入学生的第一次和第二次考试成绩并打分。所有标记必须在输入时生效,无效标记将被拒绝。你知道吗

我们可以为学生的姓氏创建一个列表,但不知道如何从那里开始创建两个列表,其中有测试1和2的标记,需要链接到一个特定的姓氏。他们还没有学过词典,在我的研究中,我发现这可能是一种选择,但不能用来解决问题。你知道吗

任何帮助都将不胜感激。你知道吗


Tags: 代码标记列表链接作业数组学生词典
1条回答
网友
1楼 · 发布于 2024-05-15 20:58:35

使用字典:

people = {}
for _ in range(30):
    surname = input('surname: ')
    ok = False
    while not ok:
        try:
            test_1 = int(input('test 1 score: '))
            test_2 = int(input('test 2 score: '))
            if not (0 <= test_1 <= 50 and 0 <= test_2 <= 50): raise ValueError
            ok = True
        except ValueError:
            print('please enter integers between 0 and 50')
    people[surname] = {'test 1': test_1, 'test 2': test_2, 'total': test_1 + test_2}

然后,在所有的条目之后,您可以通过以下方式轻松地获得结果:

people['charles']['test 1']
people = {}
for _ in range(30):
    surname = input('surname: ')
    ok = False
    while not ok:
        try:
            test_1 = int(input('test 1 score: '))
            test_2 = int(input('test 2 score: '))
            if not 0 < test_1 < 50 and 0 < test_2 < 50: raise ValueError
            ok = True
        except ValueError:
            print('please enter integers between 0 and 50')
    people[surname] = {'test 1': test_1, 'test 2': test_2, 'total': test_1 + test_2}

如果你不应该使用字典,那么下一个最好的方法可能是使用四个列表:一个用于姓氏,两个用于测试分数,一个用于总分。你知道吗

看起来像是:

people = []
test_1_scores = []
test_2_scores = []
total_scores = []
for _ in range(30):
    surname = input('surname: ')
    ok = False
    while not ok:
        try:
            test_1 = int(input('test 1 score: '))
            test_2 = int(input('test 2 score: '))
            if not (0 <= test_1 <= 50 and 0 <= test_2 <= 50): raise ValueError
            ok = True
        except ValueError:
            print('please enter integers between 0 and 50')
    people.append(surname)
    test_1_scores.append(test_1)
    test_2_scores.append(test_2)
    total_scores.append(test_1 + test_2)

然后,您可以通过使用people列表中姓氏的相应索引索引所需列表来获得结果:

test_1_scores[people.index('charles')]

相关问题 更多 >