0

我需要实现一个名为运动员的类​​,该类采用__init__(self,names,fastest_time) 另一个名为的方法fastest_time,该方法将显示最快运动员的姓名和时间:

到目前为止,我有这个:

class Athlete:
    def __init__(self,names,ftime):
        self.name=names
        self.fastest=ftime
    def fastest_athlete(self):


names=(['sara','jam','mary'])
times=([90,50,75])
a=Athlete(name,ftime)
a.fastest_athlete()

问题:不知道是否需要遍历数组名'times'?不知道如何实现方法fastest_time..请帮助

4

5 回答 5

2

您应该遍历数组以创建Athletes.

>>>Athletes = [Athlete(name, time) for name, time in zip(names, times)]    
>>>Athletes[0].name
sara
>>>Athletes[1].name
jam

好吧,要找到最快的运动员,您可以使用maxmin功能。

>>>min(Athletes, key = lambda a : a.fastest)

但是您应该注意,这min()是在包含Athletes 的数组上完成的,而不是在Athlete本身上完成的。如果你想找到最快的Athlete,你可能需要类之AthleteContainer类的东西。

于 2013-03-16T20:21:21.543 回答
1

由于最快的运动员不依赖于具体实例,因此它更适合作为静态方法:

class Athlete:
    # ...
    @staticmethod
    def fastest_athlete(athletes):
        return reduce(lambda x, y: x if x.fastest < y.fastest else y, athletes)

# ...
athletes = [Athlete(name, time) for name, time in zip(names, times)] 
fastest = Athlete.fastest_athlete(athletes)
于 2013-03-16T20:30:41.990 回答
0

如果您想fastest_athlete成为运动员班的一员,那么您的Athlete班级应该能够覆盖所有运动员。

fastest_athlete会返回一个列表,因为可能会有更多的运动员跑出最佳时间。

athletes=[] # stores all athletes 

class Athlete:
    def __init__(self,names,ftime):
        self.name=names
        self.fastest=ftime
        athletes.append(self)
    def fastest_athlete(self):
        besttime= min([athlete.fastest for athlete in athletes])
        return [athlete.name for athlete in athletes if athlete.fastest==besttime]



names=(['sara','jam','mary'])
times=([90,50,75])

for a, t in zip(names, times):
    last_athlete=Athlete(a, t)

print last_athlete.fastest_athlete()
于 2013-03-16T20:36:52.400 回答
0

如果您只想遍历数组,self.name则:

for name in self.names:
    # Do something

但对于实际问题:

def fastest_athlete(self):
    combined = zip(self.names, self.fastest)

    #Note that this will return the athlete with the first fastest time if there are dupes
    index = self.fastest.index(min(self.fastest))

    #If you want multiples:
    indices = [i for i,n in enumerate(self.fastest) if n == min(self.fastest)]

    #Either return the list (combined[0] is the athlete's name, combined[1] is the associated time) or print it here.
    return combined[index]

但是,我同意另一位评论者的观点——运动员应该是单独的对象,而不是集合。

于 2013-03-16T20:36:54.340 回答
0

您可以覆盖该__gt__方法并使用 python 的max函数。此外,每个班级应代表一名运动员,而不是运动员名单。

>>> class Athlete:
    name = None
    time = None

    def __init__(self, name, time):
        self.name = name
        self.time = time

    def __gt__(self, other):
        return self.time > other.time

>>> names = ['sara', 'jam', 'mary']
>>> times = [90 ,50 , 75]
>>>
>>> athletes = [Athlete(name, time) for name, time in zip(names, times)]
>>>
>>> fastest = max(athletes)
>>> fastest.name
'sara'
>>> fastest.time
90
于 2013-03-16T20:40:53.027 回答