试图用python中的名字计算最高分

时间:2014-02-11 01:27:48

标签: python average stat highest

grade=[]
names=[]
highest=0



cases=int(input('Enter number of cases: '))
for case in range(1,cases+1):
    print('case',case)

    number=int(input('Enter number of students: '))
    for numbers in range (1,number+1):

        name=str(input('Enter name of student: '))
        names.append(name)
        mark=float(input('Enter mark of student:'))
        grade.append(mark)


    print('Case',case,'result') 
    print('name',list[list.index(max(grade))])
    average=(sum(grade)/number)
    print('average',average)
    print('highest',max(grade))
    print('name',names[grade.index(max(grade))])

我想打印最高分的学生姓名。除了列表,我还没有学到任何东西。没有字典..没什么。我想知道我该怎么做? 我也得到这个错误! builtins.AttributeError:'str'对象没有属性'append'。救命。谢谢! :d

2 个答案:

答案 0 :(得分:1)

  1. for number in range (1,number+1):
    

    不要为不同的事物重用变量名称,调用其中一个numbers和另一个number

    numbers=int(input('Enter number of students: '))
    for number in range (1,numbers+1):
    
  2. 您在开头列出了name列表:

    name=[]
    

    但是在这里为它分配一个输入:

    name=str(input('Enter name of student: '))
    

    您将新名称附加到自身:

    name.append(name)
    

    这是不可能的,因为name在输入之后不再是列表而是字符串。再次为不同的事物使用不同的变量名称会有所帮助调用数组names和单个输入name

    names = []
    #...
    name=str(input('Enter name of student: '))
    names.append(name)
    
  3. 在这里:

     print('name',list[list.index(max(grade))])
    

    list是内置类型,而不是您的变量之一,因此您要做的是索引类型,而不是特定列表。如果要在特定列表上调用index,请使用该列表的变量名称。 grade.index(...)会在grade中找到与通过的成绩匹配的具体位置,然后您可以使用此位置获取相应的名称,因为您知道该名称位于{{1}中的相同位置}:

    names

答案 1 :(得分:0)

这是一个更精心的版本;通过它可以让你更好地掌握语言。

from collections import namedtuple
import sys

# Python 2/3 compatibility shim
if sys.hexversion < 0x3000000:
    inp, rng = raw_input, xrange    # Python 2.x
else:
    inp, rng = input, range         # Python 3.x

def type_getter(type):
    """
    Build a function to prompt for input of required type
    """
    def fn(prompt):
        while True:
            try:
                return type(inp(prompt))
            except ValueError:
                pass        # couldn't parse as the desired type - try again
    fn.__doc__ = "\n    Prompt for input and return as {}.\n".format(type.__name__)
    return fn
get_int   = type_getter(int)
get_float = type_getter(float)

# Student record datatype
Student = namedtuple('Student', ['name', 'mark'])

def get_students():
    """
    Prompt for student names and marks;
      return as list of Student
    """
    students = []
    while True:
        name = inp("Enter name (or nothing to quit): ").strip()
        if name:
            mark = get_float("Enter {}'s mark: ".format(name))
            students.append(Student(name, mark))
        else:
            return students

def main():
    cases = get_int("How many cases are there? ")
    for case in rng(1, cases+1):
        print("\nCase {}:".format(case))
        # get student data
        students = get_students()
        # perform calculations
        avg = sum((student.mark for student in students), 0.) / len(students)
        best_student = max(students, key=lambda x: x.mark)
        # report the results
        print(
            "\nCase {} average was {:0.1f}%"
            "\nBest student was {} with {:0.1f}%"
            .format(case, avg, best_student.name, best_student.mark)
        )

if __name__=="__main__":
    main()

的运行方式如下:

How many cases are there? 1

Case 1:
Enter name (or nothing to quit): A
Enter A's mark: 10.
Enter name (or nothing to quit): B
Enter B's mark: 20.
Enter name (or nothing to quit): 

Case 1 average was 15.0%
Best student was B with 20.0%