Python 不可订阅

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4123603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:22:04  来源:igfitidea点击:

Python unsubscriptable

pythontypeerror

提问by Theodor

What does unsubscriptablemean in the context of a TypeError as in:

unsubscriptable在 TypeError 的上下文中是什么意思,如下所示:

TypeError: 'int' object is unsubscriptable

EDIT: Short code example that results in this phenomena.

编辑:导致这种现象的短代码示例。

a=[[1,2],[5,3],5,[5,6],[2,2]]
for b in a:
    print b[0]

> 1
> 5
> TypeError: 'int' object is unsubscriptable

采纳答案by kichik

It means you tried treating an integer as an array. For example:

这意味着您尝试将整数视为数组。例如:

a = 1337
b = [1,3,3,7]
print b[0] # prints 1
print a[0] # raises your exception

回答by camh

You are trying to lookup an array subscript of an int:

您正在尝试查找 int 的数组下标:

>>> 1[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is unsubscriptable

That is, square brackets []are the subscript operator. If you try to apply the subscript operator to an object that does not support it (such as not implementing __getitem__()).

也就是说,方括号[]是下标运算符。如果您尝试将下标运算符应用于不支持它的对象(例如未实现__getitem__())。

回答by Sean Reifschneider

The problem in your sample code is that the array "a" contains two different types: it has 4 2-element lists and one integer. You are then trying to sub-script every element in "a", including the integer element.

您的示例代码中的问题是数组“a”包含两种不同的类型:它有 4 个 2 元素列表和一个整数。然后,您尝试为“a”中的每个元素添加下标,包括整数元素。

In other words, your code is effectively doing:

换句话说,您的代码正在有效地执行以下操作:

print [1,2][0]
print [5,3][0]
print 5[0]
print [5,6][0]
print [2,2][0]

That middle line where it does "5[0]" is what is generating the error.

它执行“5[0]”的中间线是产生错误的原因。