【问题标题】:How to find the minimum from a list of objects?如何从对象列表中找到最小值?
【发布时间】:2021-06-23 22:16:41
【问题描述】:

我想写一个方法来找到得分最低的人并打印他的其他详细信息。

如果我写一个方法来找到最小值,我就无法打印他的其他详细信息。 有问题的是,它被告知在另一个名为 Team 的类中编写“getMinRuns”。

python3

class Player:
    def __init__(self,playerName,playerCountry,playerScore):
        self.playerName=playerName
        self.playerCountry=playerCountry
        self.playerAge=playerScore

class Team:
    def getMinRuns(p):
        pass

n=int(input())
p=[]

for i in range(n):
    name=input()
    country=input()
    score=int(input())
    p.append(Player(name,country,score))
Team.getMinRuns(p)

【问题讨论】:

    标签: python-3.x list object listobject python-object


    【解决方案1】:

    当您将对象列表传递给函数 getMinRuns 时,您可以遍历列表并读取每个对象的分数,这将帮助您稍后找到最低得分对象,您可以在末尾打印或写入该对象的详细信息函数。

    def getMinRuns(p):
        min_score_index = 0
        for i in range(1, len(p)):
            if p[i].playerAge < p[min_score_index].playerAge:
                min_score_index = i
    
        print(p[min_score_index].playerName, p[min_score_index].playerCountry, 
        p[min_score_index].playerAge)
    

    我希望这可以解决您的问题,如果您有任何问题,请随时提出问题。

    【讨论】:

      猜你喜欢
      • 2017-10-26
      • 1970-01-01
      • 2020-12-02
      • 2021-10-10
      • 1970-01-01
      • 2014-06-01
      • 2020-03-08
      • 2019-12-09
      • 2016-05-22
      相关资源
      最近更新 更多