如何修复Python中的“IndexError:list index out out range”

2024-09-28 03:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如,当给予

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


Tags: nameinpy列表forindexnames排序
3条回答

出现此错误是因为以下几行:

for name in names:
    taskcount.pop(0)

taskcount = list(unique_everseen(taskcount))

删除这些也会删除错误。在

但是,您的代码仍然不会返回预期的顺序,因为它将更多的时间放在第一位。您将在结尾处得到[('carl', [3, 110]), ('usain', [3, 109]), ('tyson', [1, 11])],或者当返回{}时,因为carl的总时间比usain长。在

它应该只是调整sortedDict = sorted(ndict.items(),reverse = True , key=lambda kv: kv[1])行,这样它就可以按时间的相反方向进行排序了。在

 from collections import Counter

data_release = ["tyson 0:11", "usain 0:12", "carl 0:30", "carl 0:20", "usain 0:40", "carl 1:00", "usain 0:57"]


def sorted_data(data):
    temp_data = []
    for item in data:
        item = item.split()[0]
        temp_data.append(item)

    temp_dict = dict(Counter(temp_data))
    sorted_list = sorted(temp_dict.items(), key=lambda d: - d[1])

    result = []
    for temp_tuple in sorted_list:
        result.append(temp_tuple[0])

    return result


    print(sorted_data(data_release))

充分利用python集合库,问题会更简单!在

另一个答案解决了这个问题,但我想建议一个更实用的方法:

data = ["tyson 0:11", "usain 0:12", "carl 0:30", "carl 0:20", "usain 0:40", "carl 1:00", "usain 0:57"]

from itertools import groupby
from operator import itemgetter

def process_time(t):
    minutes, seconds = map(int, t.split(':'))
    return 60 * minutes + seconds

def sort_key(pair):
    return (-len(pair[1]), min(pair[1]))

grouped = groupby(sorted(task.split() for task in data), 
                  key=itemgetter(0))

processed = {key: [process_time(time) for name, time in group] 
             for key, group in grouped}

print(processed)
print([name for name, time in sorted(processed.items(), key=sort_key)])

输出:

^{pr2}$

首先,我们使用sorteditertools.groupby对输入数据中的每个条目进行排序和分组。这允许我们以更结构化的形式获取数据dict,其中键是名称,值是lists次。在

在此过程中,我们还将表示时间的字符串处理为以秒为单位的整数。在

接下来,我们要根据dict的值对它们的键进行排序,首先按长度的降序(因为值的长度是任务数),然后按最小时间的递增顺序。在

这是通过指定一个键函数sort_key来完成的,该函数在这里返回一个tuple。键函数的作用是,输入将被排序,就好像键函数被应用于它一样。在

tuples按其第一个元素排序,然后按第二个元素排序,依此类推,直到所有连接都断开或到达最后一个元素为止。在本例中,我们有一个2元组,其中第一个元素是输入的长度,第二个元素是最小值。在

请注意,前者是负数,因为sorted默认情况下按升序排序;通过对长度求反,我们颠倒了排序顺序。在仅对一个元素进行排序的情况下,可以传递reverse=True,但这里我们有两个排序顺序不同的排序。在

所有这些的结果是,我们执行所需的排序以获得答案。在

相关问题 更多 >

    热门问题