Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

python - How can I find max number among numbers in this code?

class student(object):

    def student(self):
        self.name=input("enter name:")
        self.stno=int(input("enter stno:"))
        self.score=int(input("enter score:"))
    def dis(self):
        print("name:",self.name,"stno:",self.stno,"score:",self.score)
    def stno(self):
        return self.stno
    def name(self):
        return self.name
    def score(self):
        return self.score


y=[]
j=0
while(j<3):
    a=student()
    a.student()
    y.append(a)
    j+=1


for st in y:
    st.dis()

for b in y:
    max_v=b.score
    if max_v<b.score:
        max_v=b.score
print(max,b.stno,b.score)

I write above code, but I think there is a problem with finding maximum number amongst numbers as I am trying this code and I cannot find any solution for that. Do you have any opinion to improve this part of code. Many Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Similar to Rawing's answer, but instead of a lambda, you can use operator.attrgetter()

from operator import attgetter

class ...
    # You class code remains unchanged

y=[]
j=0
while(j<3):
    a=student()
    a.student()
    y.append(a)
    j+=1


max_student = max(y, key=attrgetter('score'))
print("Highest score:", max_student.name, max_student.score)

Produces output like this:

enter name:dan
enter stno:3
enter score:3
enter name:emily
enter stno:20
enter score:20
enter name:frank
enter stno:1
enter score:1
Highest score: emily 20

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...