Python通过循环提高效率

时间:2017-12-15 14:01:14

标签: python python-2.7 loops

我有一些代码,看起来非常重复,我想知道如何通过将变量放入循环来提高效率,尽管变量名称存在差异。

    if int(self.answer1) == int(self.studentAnswer1):
        self.score = int(self.score) + 1
        self.questionsAsked = self.questionsAsked + 1
        self.updateProgressBar()

    else:
        self.display = "Sorry the correct answer was " + str(self.answer1)
        self.wrongAnswer()

    self.correctAnswer = int(self.answer1)
    self.input = int(self.studentAnswer1)
    self.type = str(self.a) + " multiplied by 1000, to convert KG to Grams"
    self.insertAnswer()


    if int(self.answer2) == int(self.studentAnswer2):
        self.score = int(self.score) + 1
        self.questionsAsked = self.questionsAsked + 1
        self.updateProgressBar()

    else:
        self.display = "Sorry the correct answer was " + str(self.answer2)
        self.wrongAnswer()

    self.correctAnswer = int(self.answer2)
    self.input = int(self.studentAnswer2)
    self.type = str(self.a) + " divide by 1000, convert Grams to KG"
    self.insertAnswer()

它目前正如预期的那样工作。

2 个答案:

答案 0 :(得分:1)

其他答案的替代方法,即迭代索引和从列表中提取,都使用zip

例如:

answers = [whatever]
student_answers = [whatever]
for answer, student_answer in zip(answers, student_answers):
  ...

这完全符合它的外观。 zip([1, 2, 3], [4, 5, 6]) == [(1, 4), (2, 5), (3, 6)]

答案 1 :(得分:0)

试试这个;

answer = [answer1, answer2];
student_answer= [studentAnswer1, studentAnswer2];

for i in range (len(answer)){
       if int(self.answer[i]) == int(self.student_answer[i]):
            self.score = int(self.score) + 1
            self.questionsAsked = self.questionsAsked + 1
            self.updateProgressBar()

        else:
            self.display = "Sorry the correct answer was " + str(self.answer[i])
            self.wrongAnswer()

        self.correctAnswer = int(self.answer[i])
        self.input = int(self.student_answer[i])
        self.type = str(self.a) + " multiplied by 1000, to convert KG to Grams"
        self.insertAnswer()
  }