TypeError: list indices must be integers or slices, not list"

时光毁灭记忆、已成空白 提交于 2021-01-28 19:42:12

问题


I am trying the following code but I have the problem with the indices and having the following error

if int( NewList[i][1] ) <120:
TypeError: list indices must be integers or slices, not list

In this case, the script should delete the the first 2 lists (['0', '30', '100'], ['20', '100', '54'])

and how can I replace NewList[i][1] when the conditions don't meet for the first time? In this case, I want to replace NewList[2][1] = 150 by 120.

Here is my code:

def newdef ():
    NewList = [['0', '30', '100'], ['20', '100', '54'], ['100', '150', '40'],
    ['150', '400', '30'], ['400', '450', '25'], ['450', '500', '20'],
    ['500', '550', '12'], ['550', '690', '6']]
    for i in NewList:
        if int(NewList[i][1]) <120:
            del NewList[i]
        else:
            pass
    return NewList
print (newdef())

回答1:


here i will be a sublist instead of an index.

Try this:

def newdef():
    NewList = [['0', '30', '100'], ['20', '100', '54'], ['100', '150', '40'],['150', '400', '30'], ['400', '450', '25'], ['450', '500', '20'],['500', '550', '12'], ['550', '690', '6']]
    res = []
    for  i in range(len(NewList)):
        if int(NewList[i][1]) >= 120:
            res.append(NewList[i])
    return res
print (newdef())



回答2:


You were using the nested list as if it were an index, but it was a list object. To get the index of the lists you would need to use enumerate:

list_of_lists = [[1], [2]]
for idx, list_ in enumerate(list_of_lists):
    print(idx)

This should work and is more readable.

def newdef():
    input_list = [
        ['0', '30', '100'], ['20', '100', '54'], ['100', '150', '40'],
        ['150', '400', '30'], ['400', '450', '25'], ['450', '500', '20'],
        ['500', '550', '12'], ['550', '690', '6']
    ]
    output_list = []
    for sub_list in input_list:
        if int(sub_list[1]) >= 120:
            output_list.append(sub_list)
    return output_list

print(newdef())


来源:https://stackoverflow.com/questions/61441230/typeerror-list-indices-must-be-integers-or-slices-not-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!