的Martijn已经回答了你的问题,所以这里有一些言论和代码风格技巧:
新式的类从object
你既有运动员的名字和他们的时间推导,那些属于一起作为字典中的键值对,而不是两个单独的列表
不要使用类的方法里面print语句,一类方法应该返回一个对象,你那么可以打印
如果你有更多的日你想输入时间的2名运动员?如果你做运动员的函数的参数个数,你可以添加一个可变数目athlethes的
给描述性的变量名(不mylist),不使用的内置函数的名称(如list)作为变量名
您希望在整个班级中使用的变量可以通过__init__方法初始化。
进行打印,使用format功能,而不是使用逗号
考虑到这些,我想你的代码改写为这样的:
from collections import defaultdict
class Athlete(object): # see (1)
def __init__(self): # see (6)
self.athlete_times = defaultdict(str) # see (2)
def add_athletes_and_times(self, n): # see (4)
for i in range(n):
self.name = raw_input("Enter name: ")
self.fastest_time = input("time (in seconds): ")
self.athlete_times[self.fastest_time] = self.name
def get_fastest_time(self):
return min(self.athlete_times) # see (3)
if __name__ == '__main__': # see (8)
x = Athlete()
x.add_athletes_and_times(2)
for fast_time in x.athlete_times:
print "The fastest time of athlete {0} is {1} seconds.".format(
x.athlete_times[fast_time], fast_time) # see (7)
fastest_time = x.get_fastest_time()
print "The overall fastest time is: {0} seconds for athlete {1}.".format(
fastest_time, x.athlete_times[fastest_time])