Overlap the list? How do you do it?

Asked 2 years ago, Updated 2 years ago, 46 views

import collections
import operator
Student = collections.namedtuple("Student", "name stdid grade" )
e=int(input("Input loop count: "))
list=[]
for list in range (e):

    name1=input("Input name: ")
    stdid1 =int(input("Input student id: "))
    grade1= int(input("Input grade: "))


    std=Student(name=name1, stdid=stdid1, grade=grade1)

list=sorted(list,key = attrgetter("id"))
print("===============================")
print(std)

The expression is repeated as many times as the number entered in e, and only the last values entered in the list are included. How do I save the numbers I entered before that? Also, there is an error saying that attrgetter is not defined, so if you import operator, you don't have to define attrgetter, right?

python list

2022-09-20 22:23

1 Answers

The code you wrote shows the result you mentioned because you are constantly overwriting the Student made with the last values entered in std.

Declare a separate list to save the student and add std to the list

And to use the function inside the imported module,

Use it in the form of operator.attrgetter() or

You must import in the form of from operator import attrgetter.


2022-09-20 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.