简体   繁体   English

如何修复此列表索引超出范围错误

[英]How to fix this list index out of range error

I want to perform column subtraction. 我想执行列减法。 for example [[0,2],[2,5],[3,11]] for this I want to perform (5-2),(11-5). 例如,[[0,2],[2,5],[3,11]]为此,我要执行(5-2),(11-5)。 then find which has the maximum difference.so for that I created a dictionary and store the differences along with its pair. 然后找到最大的差异。为此,我创建了一个字典,并将差异及其对存储在一起。 for example difference of (5-2) is stored with 0, and difference of (11-5) is stored with 2. 例如(5-2)的差异存储为0,(11-5)的差异存储为2。

error is : 错误是:

Traceback (most recent call last): File "/home/viki/Music/keypress.py", line 14, in keypressTime(l) File "/home/viki/Music/keypress.py", line 10, in keypressTime d = x[i+1][1] - x[i][1] IndexError: list index out of range 追溯(最近一次通话最近):keypressTime(l)中第14行的文件“ /home/viki/Music/keypress.py”,keypressTime d中第10行的文件“ /home/viki/Music/keypress.py” = x [i + 1] [1]-x [i] [1] IndexError:列表索引超出范围

import operator

l = [[0,2],[2.4],[0,8],[3,9],[5,20]]

def keypressTime(x):
    dic = {}
    d = 0
    for i in range(len(x)-1):
        if i <(len(x)-1):
            d = x[i+1][1] - x[i][1]
            dic["i"] = d
    return max(dict.items(),key=operator.itemgetter(1))[0]

keypressTime(l)

There is a typo in the variable declaration of l. l的变量声明中有一个错字。 l = [[0,2], [2.4] ,[0,8],[3,9],[5,20]] -> change 2.4 to 2,4 l = [[0,2], [2.4] ,[0,8],[3,9],[5,20]]->将2.4更改为2,4

And dict.items() should probably be dic.items() dict.items()应该是dic.items()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM