python错误:TypeError:列表索引必须是整数或片,而不是列表

python错误:TypeError:列表索引必须是整数或片,而不是列表,python,Python,我正在写这段python代码,我得到了一个错误。我在互联网上搜索过StackOverflow,但没有任何东西适合我 错误: TypeError:列表索引必须是整数或切片,而不是列表(第7行) 我的代码: products = [ [ 'name', 'id', 'number in stock', 'price ($)' ], ['iPhone', '1', '100', '999'] ] def inst

我正在写这段
python
代码,我得到了一个错误。我在互联网上搜索过StackOverflow,但没有任何东西适合我

错误:
TypeError:列表索引必须是整数或切片,而不是列表(第7行)

我的代码:

products = [
    [
        'name',
        'id',
        'number in stock',
        'price ($)'
    ],
    ['iPhone', '1', '100', '999']
]

def instore(item):
    for x in products:
        if products[x][0] == item:
            print(products[x][0] + ': \n id: ' + products[x][1] + ' In Stock: ' + products[x][2])

for循环中的
x
已经是
产品中的相关项。它不是计数器,不需要说
products[x]

for x in products:
   if x[0] == item:
       ...

(此外,您可能希望在此处使用字典而不是列表;然后您可以直接查找
产品[项目]
,而不是每次迭代列表。)

变量
x
产品
列表中的每个项目一起分配
for
语句,而不是索引,因此,您应该将其作为
产品
列表中的一项进行访问:

def instore(item):
    for x in products:
        if x[0] == item:
            print(x[0] + ': \n id: ' + x[1] + ' In Stock: ' + x[2])

正如其他人已经告诉你的那样,
x
是列表的一个元素,而不是一个计数器变量。如果你还想使用计数器,你可以这样做

for x in range(len(products)):
   if products[x][0] == item:
       ...

range(n)
函数创建从
0到n-1的范围(列表)
。您可以从.

中阅读有关范围的更多信息,因为您不是迭代列表中的索引,而是迭代产品列表中以变量“x”形式存在的元素。我想你会明白这一点的。然后检查前面的答案是否正确

第7行是
。如果x[0]==项: