TypeError:列表索引必须是整数或切片,而不是列表 [英] TypeError: list indices must be integers or slices, not list

查看:110
本文介绍了TypeError:列表索引必须是整数或切片,而不是列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

array =一种具有3列的列表,其中包含数据的行数不受限制.

array = some kind of list with 3 columns and unlimited amount of rows with data inside of it.

Volume = array[0][2] 
counter = 0
for i in array: 
    if Volume == array[i][2]: #<------ why is this line a problem? 
        counter += 1

推荐答案

这是一个经典的错误.在您的情况下,i已经是array(即另一个列表)中的元素, not 的索引是array( not int),因此

This is a classic mistake. i in your case is already an element from array (i.e. another list), not an index of array (not an int), so

if Volume == i[2]:
    counter += 1

请确保至少经历 Python的开头教程,因为这是非常简单和基本的内容.

Please, make sure to go at least through the beginning of Python tutorial, because this is very simple and fundamental stuff.

我也建议您遵循命名约定:变量通常是小写字母(volume,而不是Volume).在这种情况下,i具有误导性. rowelem更合适.

Also I would advise to stick to naming conventions: variables are normally lower-case (volume, not Volume). In this case i is misleading. row or elem would be much more suitable.

这篇关于TypeError:列表索引必须是整数或切片,而不是列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆