繁体   English   中英

TypeError:'int'对象在Python枚举中没有属性'__getitem__'

[英]TypeError: 'int' object has no attribute '__getitem__' in Python enumerate

嗨,我有如下代码

我的tupleList是= [(0, '1.example'), (1, '2.example'), (2, '3. example'), (3, '4. example'), 0]

Index = [x for x, y in enumerate(tupleList[0]) if y[0] == control]
self.list["list_key"].append(tupleList[0][Index[0]][1])

并且我的控制变量是1并键入int,我试图在元组中达到“ 2.example”,

出错

TypeError: 'int' object has no attribute '__getitem__' in Python

更改我的元组是= [('E', '1 examp'), ('H', '2 examp'), 'E']

像这样,我的控制变量是'E'不会有问题,代码可以正常工作,但是我更改了tupleList = [(0, '1.example'), (1, '2.example'), (2, '3. example'), (3, '4. example'), 0]并将控制变量设置为1,我得到了错误

我该如何处理此tupleList

这是因为字符串是可迭代的,但整数不是。

您可以显式检查整数:

[x for x, y in enumerate(tupleList[0]) if not isinstance(y, int) and y[0] == control]

或更笼统地说:

from typing import Iterable
[x for x, y in enumerate(tupleList[0]) if isinstance(y, Iterable) and y[0] == control]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM