如何将索引添加到索引

时间:2017-07-26 01:14:05

标签: python

行。这是我第一次提问,所以请不要对我太复杂。我正在尝试设置我的Python程序,以便它列出三个不同类别的分数:测验,程序和测试,并将它们放在一个列表中。我的代码如下所示:

QUIZ_GRADES = int(input("How many quiz grades? "))

PROGRAM_GRADES = int(input("How many program grades? "))

TESTS = int(input("How many tests? "))

def main():

globalConstantList = [QUIZ_GRADES, PROGRAM_GRADES, TESTS]

scoreList = [0] * (QUIZ_GRADES + PROGRAM_GRADES + TESTS)

returnedScoresList = getGrades(globalConstantList,scoreList)

#totalList(totalScore[scores])

#userOutput()

print(returnedScoresList)


def getGrades(globalConstantList,scoreList):

    for eachScore in globalConstantList:

    #totalScoreList = 0.0

    index = 0

        for index in range(QUIZ_GRADES):

            print("What is the score for quiz", index + 1)

            scoreList[index] = float(input())

        for index in range(PROGRAM_GRADES):

            print("What is the score for program", index + 1)

            scoreList[index] = float(input())

        for index in range(TESTS):

            print("What is the score for test", index + 1)

            scoreList[index] = float(input())

        return scoreList


main()

(对不起,如果代码示例中没有放置所有内容 - FYI语法正确。)

这是我的问题:每次运行我的代码时,它都会将QUIZ_GRADES所有值添加到scoreList[]列表中QUIZ_GRADES } for-loop,但是当我运行PROGRAM_GRADES for循环时,它将取出我的原始值(来自QUIZ_GRADES)并放入PROGRAM_GRADES)。例如,如果我为我的测验分数输入99,98和97,为我的计划分数输入96,它将删除最初的99并放在96中。有没有办法可以填写整个{{1}没有删除我的任何价值观?谢谢

2 个答案:

答案 0 :(得分:0)

你可能想写

for index in range(QUIZ_GRADES):
  index+=1
  print("What is the score for quiz", index)
  scoreList[index] = float(input())

和其他类似的循环相似。 print(..,index + 1)不会增加索引,并且每个for循环索引从0开始。因此,在每个for循环的开头,scoreList [index]计算得分列表[0]并覆盖你插入的内容在之前的循环中。

请注意,有更优雅的方法可以对此进行编码。还要检查append()方法

答案 1 :(得分:0)

我认为你应该附加到列表中:

scoreList.append(float(input()))

在每个循环中,假设函数启动时scoreList为空。因此,您的代码应该成为:

def main():
    globalConstantList = [QUIZ_GRADES, PROGRAM_GRADES, TESTS]
    # scoreList = [0] * (QUIZ_GRADES + PROGRAM_GRADES + TESTS)
    returnedScoresList = getGrades(globalConstantList)
    #totalList(totalScore[scores])
    #userOutput()
    print(returnedScoresList)

def getGrades(globalConstantList):
    scoreList = []
    for eachScore in globalConstantList:
        #totalScoreList = 0.0
        index = 0
        for i in range(QUIZ_GRADES):
            index += 1
            print("What is the score for quiz", index)
            scoreList.append(float(input()))
        for i in range(PROGRAM_GRADES):
            index += 1
            print("What is the score for program", index)
            scoreList.append(float(input()))
        for i in range(TESTS):
            index += 1
            print("What is the score for test", index)
            scoreList.append(float(input()))
    return scoreList

main()

或者使用start的{​​{1}}和stop参数:

range()