我可能会使用字典而不是顶级变量来包含跑步者的字段:
from turtle import Turtle
from operator import itemgetter
from random import randint
STARTING_POINT = (0, 0)
RUNNERS = ["Maria", "Jaquina", "Toino", "Celeste", "Tia"]
def show_winners(field):
return sorted(((turtle.distance(STARTING_POINT), name) for name, turtle in field.items()), key=itemgetter(0), reverse=True)
field = {runner: Turtle() for runner in RUNNERS}
for turtle in field.values(): # simulate a race for example purposes
turtle.forward(randint(10, 100))
print(show_winners(field))
输出
% python3 test.py
[(75.0, 'Celeste'), (53.0, 'Toino'), (52.0, 'Maria'), (44.0, 'Tia'), (24.0, 'Jaquina')]
%
结果包括距离,以便您可以看到它正在工作。如果您只需要名称,则可以按照@SimonR (+1) 解决方案的行简化代码:
def show_winners(field):
return sorted(field, key=lambda name: field[name].distance(STARTING_POINT), reverse=True)
并折腾import
of itemgetter
(这只是为了避免在平局的情况下出现错误。)
% python3 test.py
['Toino', 'Jaquina', 'Tia', 'Maria', 'Celeste']
%