简体   繁体   中英

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). 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.

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

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 = [[0,2], [2.4] ,[0,8],[3,9],[5,20]] -> change 2.4 to 2,4

And dict.items() should probably be dic.items()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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