如何调用存储在列表列表中的类实例?

时间:2014-11-30 16:29:04

标签: python list class instance

我在Kubuntu 14.04中使用Python 2.7.6;尝试(为了我自己的启发)使用为每个单元格实例化的单个类来实现Conway的Life,以执行“元胞自动机”工作。在这个过程中,我将一个实例存储在列表列表的每个成员中。问题是,当我尝试在迭代列表的索引时调用实例方法时,我收到错误:TypeError: 'int' object has no attribute '__getitem__'。这是我的代码:

# Conway's Life in Python -- initially with text graphics, 50x50, possibly
# with actual windowing system graphics in a later version.  Use a class
# replicated in quantity (2500!) for each cell to vastly simplify computation;

# is below worth it or not?  Would bring all four cores into computation.
# learn how to do threading to let the cells calculate in parallel, but pass
# signals to keep them in step.

class Cell(object):

  def __init__(self, coords, size):
    # coords is a tuple of x, y; size is the field height/width in cells
    self.position = coords
    self.is_live = False
    pass

  def count_neighbors(self):
    x,y = self.position
    self.neighbors = 0
    for i in range (-1, 1):
      for j in range (-1, 1):
    # add size and modulo (size - 1) to create wrapped edges
    if field[(x + i + self.xy) % (self.xy - 1)] [(y + j + 
                                  self.xy) % (self.xy - 1)]:
      ++self.neighbors
    pass

  def live_or_die (self):
    if self.neighbors < 2 or self.neighbors > 3:
      self.is_live = False
    elif self.neighbors == 3:
      self.is_live = True
    else:
      pass

# main program

extent = 4 #size of field

# create list of lists of Cell objects w/ coord tuples
# for i in range extent:
#   for j in range extent:
#     field[i[j]] = (i,j)

field = [[Cell((i, j), extent) for j in range(extent)] for i in range(extent)]

# insert population setting here

# insert population setting here

for i in range (extent):
  for j in range (extent):
    field[i[j]].count_neighbors()

for i in range (extent):
  for j in range (extent):
    field[i[j]].live_or_die()

最后两个for循环将包含在while中以便继续操作,一旦我弄清楚如何创建初始填充并以受控方式停止程序。显然,一旦我调试了迭代,extent将被设置得更高(50x50在Cell的方法中添加变量之前仅使用了大约5.5 MiB RAM,所以我应该能够在在图形模式下使用单个像素的屏幕尺寸,如果这不会太慢 - 每秒几步可以快速满足我的口味。)

问题是,我没有看到单独调用存储在Cell中的field实例的方法。我认为这里的问题是我如何嵌套列表,但它们必须嵌套,不是吗? j列表是i列表的成员。

完整的tracebacK:

Traceback (most recent call last):
  File "PyLife.py", line 51, in <module>
    field[i[j]].count_neighbors()
TypeError: 'int' object has no attribute '__getitem__'

1 个答案:

答案 0 :(得分:1)

回溯的原因是您访问嵌套列表元素的语法。它应该是:

field[i][j].count_neighbors()

如果要访问嵌套列表中的元素

相关问题