首页 > 解决方案 > 访问元组元素时出现错误“对象不可下标”。错误取决于使用情况

问题描述

使用元组列表。访问元组的元素时,有时会收到错误消息。访问如何以以后的代码为条件?错误消息:行 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  

标签: pythontuplesgoogle-colaboratory

解决方案


unitList.append(ut)

这一行给了你错误,它在迭代期间附加了一个Unit对象。unitList即,它将Unit对象附加到元组列表中,因此它变为 [tuple, tuple, .., Unit, Unit, ..] 然后,在未来的迭代中,当代码到达item_wallname = unit[0]它不再做的时候(some tuple)[0],而是ut[0]从我可以看到不是一个可迭代的对象。

希望这有助于解释您的问题:)


推荐阅读