我有两个索引:
names=['Peter', 'Tom', 'Carl', 'Edward', 'Jake', 'Joe', 'Ken']
times=[10.01, 9.89, 9.91, 9.88, 9.91, 9.91, 9.90]
彼得的时间 10.01 ,汤姆的时间 9.89 等。
输出最快的跑步者名称和时间。
输入:按名称搜索并输出他的地点和时间
例如:
彼得:第7名(10.01)
Carl,Jake,Joe:排名第4至第6位(9.91)
对于第1部分,我尝试过:
fastest = times.index(min(times))
print(names[fastest])
我不知道如何做第2部分。
答案 0 :(得分:1)
>> names=['Peter', 'Tom', 'Carl', 'Edward', 'Jake', 'Joe', 'Ken']
>> times=[10.01, 9.89, 9.91, 9.88, 9.91, 9.91, 9.90]
>>> name_time_dict = dict(zip(names,times))
>> name_time_dict
'Ken': 9.9000000000000004, 'Jake': 9.9100000000000001, 'Edward': 9.8800000000000008, Joe': 9.9100000000000001, 'Carl': 9.9100000000000001, 'Tom': 9.8900000000000006, 'Peter': 10.01}
>>> times.sort()
>>> times.index(name_time_dict['Joe'])+1
>>> 4
>>> times.index(name_time_dict['Peter'])+1
>>> 7
答案 1 :(得分:1)
为了能够获得存储按其等级(地点)排序的跑步者的字典,您可以使用collections.OrderedDict
:
#!/usr/bin/env python3
from collections import OrderedDict, namedtuple
Runner = namedtuple('Runner', "name time rank")
names = ['Peter', 'Tom', 'Carl', 'Edward', 'Jake', 'Joe', 'Ken']
times = [10.01, 9.89, 9.91, 9.88, 9.91, 9.91, 9.90]
runners = OrderedDict((name, Runner(name, time, rank))
for rank, (time, name) in enumerate(sorted(zip(times, names)), start=1))
# 1 fastest
fastest_runner = next(iter(runners.values()))
print("fastest runner: {r.name} ({r.time})".format(r=fastest_runner))
# 2 by name
print("{r.name}: {r.rank}th place ({r.time})".format(r=runners['Peter']))
fastest runner: Edward (9.88)
Peter: 7th place (10.01)
答案 2 :(得分:0)
names=['Peter', 'Tom', 'Carl', 'Edward', 'Jake', 'Joe', 'Ken']
times=[10.01, 9.89, 9.91, 9.88, 9.91, 9.91, 9.90]
nk=zip(times,names)
nk.sort()
kk=lambda y: [a for a in list({z[0] for z in nk})].index(y)
my_contest={x[1]:{'time':x[0],'rank': kk(x[0])+1} for x in nk}
print nk
print my_contest
输出:
[(9.88, 'Edward'), (9.89, 'Tom'), (9.9, 'Ken'), (9.91, 'Carl'), (9.91, 'Jake'), (9.91, 'Joe'), (10.01, 'Peter')]
{
'Ken': {'rank': 3, 'time': 9.9},
'Jake': {'rank': 4, 'time': 9.91},
'Edward': {'rank': 1, 'time': 9.88},
'Joe': {'rank': 4, 'time': 9.91},
'Carl': {'rank': 4, 'time': 9.91},
'Tom': {'rank': 2, 'time': 9.89},
'Peter': {'rank': 5, 'time': 10.01}
}
答案 3 :(得分:0)
names=['Peter', 'Tom', 'Carl', 'Edward', 'Jake', 'Joe', 'Ken']
times=[10.01, 9.89, 9.91, 9.88, 9.91, 9.91, 9.90]
获得最快的跑步者名字和时间。
fastest_time = min(times)
fastest_runner = names[times.index(fastest_time)]
您还可以创建字典并使用它。创建字典
dictionary = dict(zip(names,times))
使用字典
In: dictionary['Carl']
Out: 9.91
答案 4 :(得分:0)
name = input()
i = name.index(name)
t = times[i]
times.sort()
print(name + ':' + str(times.index(t)))