这是根据参赛者完成的任务数(他们在输入列表中出现的次数)从大到小返回参赛者列表,如果两个参赛者的任务数相同,则按三次排序(最少到最多)。在
例如,当给予
["tyson 0:11", "usain 0:12", "carl 0:30", "carl 0:20", "usain 0:40", "carl 1:00", "usain 0:57"]
作为输入,它应该返回:
^{pr2}$然而,在按任务排序之后,我似乎不知道如何按时间排序。在
代码:
from more_itertools import unique_everseen
def winners(data):
names = []
times = []
taskcount = []
ndict = {}
for i in data:
name = i.split()[0]
time = i.split()[1]
numMin, numSec = time.split(':')
nmin = int(numMin)
nsec = int(numSec)
total = (60 * nmin) + nsec
names.append(name)
times.append(total)
index = 0
for name in names:
count = names.count(name)
taskcount.append(count)
for name in names:
taskcount.pop(0)
taskcount = list(unique_everseen(taskcount))
for name in names:
if name not in ndict:
ndict[name] = [taskcount[index], times[index]]
else:
ndict[name][1] += times[index]
index += 1
sortedDict = sorted(ndict.items(),reverse = True , key=lambda kv: kv[1])
R = [t[0] for t in sortedDict]
return R
除此之外,每当我输入某个列表时,它似乎运行良好,但每当我输入其他列表时,它就会爆炸:
Traceback (most recent call last):
File "<ipython-input-69-420jihgfedcc>", line 1, in <module>
runfile('C:/Users/User/Folder/contestWinner.py', wdir='C:/Users/User/Folder')
File "C:\Users\User\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
execfile(filename, namespace)
File "C:\Users\User\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/User/Folder/contestWinner.py", line 42, in <module>
print(winners(data))
File "C:/Users/User/Folder/contestWinner.py", line 33, in winners
ndict[name] = [taskcount[index], times[index]]
IndexError: list index out of range
有没有办法修复错误并按时间排序?抱歉,如果这真的很愚蠢,我是Python的初学者。在
出现此错误是因为以下几行:
删除这些也会删除错误。在
但是,您的代码仍然不会返回预期的顺序,因为它将更多的时间放在第一位。您将在结尾处得到}时,因为carl的总时间比usain长。在
[('carl', [3, 110]), ('usain', [3, 109]), ('tyson', [1, 11])]
,或者当返回{它应该只是调整
sortedDict = sorted(ndict.items(),reverse = True , key=lambda kv: kv[1])
行,这样它就可以按时间的相反方向进行排序了。在充分利用python集合库,问题会更简单!在
另一个答案解决了这个问题,但我想建议一个更实用的方法:
输出:
^{pr2}$首先,我们使用
sorted
和itertools.groupby
对输入数据中的每个条目进行排序和分组。这允许我们以更结构化的形式获取数据dict
,其中键是名称,值是lists
次。在在此过程中,我们还将表示时间的字符串处理为以秒为单位的整数。在
接下来,我们要根据
dict
的值对它们的键进行排序,首先按长度的降序(因为值的长度是任务数),然后按最小时间的递增顺序。在这是通过指定一个键函数
sort_key
来完成的,该函数在这里返回一个tuple
。键函数的作用是,输入将被排序,就好像键函数被应用于它一样。在tuples
按其第一个元素排序,然后按第二个元素排序,依此类推,直到所有连接都断开或到达最后一个元素为止。在本例中,我们有一个2元组,其中第一个元素是输入的负长度,第二个元素是最小值。在请注意,前者是负数,因为
sorted
默认情况下按升序排序;通过对长度求反,我们颠倒了排序顺序。在仅对一个元素进行排序的情况下,可以传递reverse=True
,但这里我们有两个排序顺序不同的排序。在所有这些的结果是,我们执行所需的排序以获得答案。在
相关问题 更多 >
编程相关推荐