[英]TypeError: list indices must be integers or slices, not list"
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 listTypeError:列表索引必须是整数或切片,而不是列表
In this case, the script should delete the the first 2 lists (['0', '30', '100'], ['20', '100', '54'])在这种情况下,脚本应该删除前 2 个列表(['0', '30', '100'], ['20', '100', '54'])
and how can I replace NewList[i][1] when the conditions don't meet for the first time?第一次不满足条件时如何替换NewList[i][1]? In this case, I want to replace NewList[2][1] = 150 by 120.
在这种情况下,我想将 NewList[2][1] = 150 替换为 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())
here i
will be a sublist instead of an index.在这里,
i
将是一个子列表而不是索引。
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())
You were using the nested list as if it were an index, but it was a list object.您正在使用嵌套列表,就好像它是一个索引,但它是一个列表 object。 To get the index of the lists you would need to use enumerate :
要获取列表的索引,您需要使用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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.