python - 访问元组元素时出现错误“对象不可下标”。错误取决于使用情况
问题描述
使用元组列表。访问元组的元素时,有时会收到错误消息。访问如何以以后的代码为条件?错误消息:行 item_wallname = unit[0] 上的“TypeError: 'Unit' object is not subscriptable”
wallList = ["L1", "T1"]
unitList = [("L1",1,"corner_out",.5),
("L1",2,"wall",2),
("L1",3,"window_a",2),
("L1",4,"wall",1),
("T1",1,"wall",8.5)]
for wallname in wallList:
for unit in unitList:
item_wallname = unit[0] # error line
if item_wallname == wallname:
item_unitID = unit[1]
item_unit_name = unit[2]
item_unit_outblocks = unit[3]
print("\nunit: " + " " + str(item_wallname) + " " + str(item_unitID))
makeWallUnit(item_wallname, item_unitID, item_unit_name, item_unit_outblocks)
如果 makeWallUnit 行处于活动状态,则会发生错误。如果它被评论,则输出如下:
unit: L1 1
unit: L1 2
unit: L1 3
unit: L1 4
unit: T1 1
编辑,添加其他代码:
def makeWallUnit(wall_name, id, name, blocks):
print("makeWallUnit()")
unitObj = makeUnit(wall_name, dir, id, name, blocks)
def makeUnit(wall_name, dir, id, name, blocks):
print('makeUnit()')
ut = Unit(wall_name, dir, id, name, blocks)
unitList.append(ut)
return ut
class Unit:
def __init__(self, direction, wall_name, unitid, unitname, blocks):
self.direction = direction
self.wall_name = wall_name
self.itemID = unitid
self.unit_name = unitname
self.blocks = blocks
self.inches = blocks * 16
self.left = 0
self.right = 0
self.start = 0
self.end = 0
解决方案
unitList.append(ut)
这一行给了你错误,它在迭代期间附加了一个Unit
对象。unitList
即,它将Unit
对象附加到元组列表中,因此它变为 [tuple, tuple, .., Unit, Unit, ..] 然后,在未来的迭代中,当代码到达item_wallname = unit[0]
它不再做的时候(some tuple)[0]
,而是ut[0]
从我可以看到不是一个可迭代的对象。
希望这有助于解释您的问题:)
推荐阅读
- c++ - 为什么C++语言的malloc函数前面要写指针类型?
- python - 将迭代循环转换为函数
- flutter - Flutter ListView 滚动索引滚动不足
- visual-studio-code - 变量声明的智能缩进
- android - 在颤动中设置自定义拾取位置
- c# - Asp 按钮导致点击时重定向和空白页面(在 ASCX 页面中)
- python - Jupyter 中自动完成 Pandas 列名的问题
- javascript - 页面中 < 之后的文本未显示
- javascript - 在对象数组中使用可选链接并进行破坏
- ajax - 使用 MVC 5 在本地主机上使用 IISExpress 的 Ajax POSTing 和 CORS 预检错误