python indexerror怎么办_如何修复Python中的“IndexError:list index out out range”

这是根据参赛者完成的任务数(他们在输入列表中出现的次数)从大到小返回参赛者列表,如果两个参赛者的任务数相同,则按三次排序(最少到最多)。在

例如,当给予["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 "", line 1, in

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

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的初学者。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值