0

我有两个索引:

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等。

  1. 输出最快的跑步者姓名和时间。

  2. 输入:按姓名搜索并输出他的地点和时间

例如:

彼得:第 7 名(10.01)

卡尔、杰克、乔:第 4-6 位(9.91)

对于第 1 部分,我尝试过:

fastest = times.index(min(times))   
print(names[fastest])

我不知道如何进行第 2 部分。

4

5 回答 5

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)
于 2012-11-25T02:57:28.927 回答
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
于 2012-11-24T11:27:19.867 回答
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
于 2012-11-24T11:18:54.357 回答
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}
    }
于 2012-11-24T11:04:52.830 回答
0
name = input() 
i = name.index(name)
t = times[i]
times.sort()
print(name + ':' + str(times.index(t)))
于 2012-11-24T11:25:00.013 回答