在python循环中有一个不断变化的变量

时间:2016-08-01 21:29:53

标签: python variables input

我正在尝试编写一个程序,要求学生姓名,一些其他数值,并通过他们的数值将它们分配给组,使所有组尽可能接近相等(通过采取列表中的最高下一个值,并将其分配给下一个组,依此类推。)

但是,我需要将他们的号码保存到某个变量及其名称,然后打印出该组的列表。 为此,我需要一个变量,每次循环进行更改以添加另一个学生。我还需要对这些数字进行排序,然后以某种方式回调他们被分类成组后他们应对的名称,我不知道如何做这些。有没有办法做到这一点,我是否必须使用另一种语言?

这是我到目前为止的代码:

from easygui import *
times = 0
name = 0


s_yn = ynbox("Would you like to enter a student?")
while s_yn == 1:
    msg = "Student's Information"
    title = "House Sorting Program"
    fieldNames = ["Name", "Grade","Athleticism (1-10)","Intellect (1-10)","Adherance to school rules (1-10)"]
    fieldValues = [] 
    fieldValues = multenterbox(msg,title, fieldNames)

    times =  times + 1

    ath = fieldValues[2]
    int_ = fieldValues[3]
    adh = fieldValues[4]
    ath = int(ath)
    int_ = int(int_)
    adh = int(adh)
    total = ath+int_+adh

    s_yn = ynbox("Would you like to enter a student?")

1 个答案:

答案 0 :(得分:0)

我相信创建一个包含与学生相关的所有变量的Student类会很好。然后,您可以将每个学生添加到一个列表中,您可以按所需的值对其进行排序,并将其划分为您想要的组数。

from easygui import *
from operator import attrgetter


class Student(object):

    def __init__(self, name, grade, athleticism, intellect, adherance):
        self.name = name
        self.grade = int(grade)
        self.athleticism = int(athleticism)
        self.intellect = int(intellect)
        self.adherance = int(adherance)
        self.total = self.athleticism + self.intellect + self.adherance

    def __str__(self):  # When converting an instance of this class to a string it'll return the string below.
        return "Name: %s, Grade: %s, Athleticism (1-10): %s, Intellect (1-10): %s, Adherance to school rules (1-10): %s"\
               % (self.name, self.grade, self.athleticism, self.intellect, self.adherance)


student_group = []
while ynbox("Would you like to enter a student?"):  # Returns 'True' or 'False' so it'll loop every time the user press 'yes'.
    message = "Student's Information"
    title = "House Sorting Program"
    field_names = ["Name", "Grade", "Athleticism (1-10)", "Intellect (1-10)", "Adherance to school rules (1-10)"]
    field_values = multenterbox(message, title, field_names)

    student = Student(*field_values)  # Unpack all elements in the list 'field_values' to the initializer.
    student_group.append(student)  # Add the student to the group 'student_group'.


# When the user has put in all the students we sort our group by 'total' (or any other value you want to sort by).
sorted_group = sorted(student_group, key=attrgetter("total"), reverse=True)

# Just as an example I divided the students into 3 groups based on their total.
best_students = sorted_group[:len(sorted_group) // 3]
average_students = sorted_group[len(sorted_group) // 3:2 * len(sorted_group) // 3]
worst_students = sorted_group[2 * len(sorted_group) // 3::]