-2

我有这段代码可以创建一个用零填充的矩阵。我想用创建蛇对象时给出的“符号”替换一些零。然后我想用我的符号替换矩阵中的零而不增加矩阵中元素的总数。

使用蛇类中的“增长”功能,我想确保仅覆盖零,但出现错误:

ValueError: (1, 4) is not in list 

当我确定该职位确实存在时!每次运行程序时错误代码都不同,因为坐标是随机生成的。这是我的代码:

class field:
 def __init__(self):

    self.table= [ [ "0" for i in range(10) ] for j in range(10) ]

  def printfield(self):
     for row in self.table:
            print (row)


Class snake:

  def __init__(self,sign):
    self.sign = sign
    self.x = random.randint(1,9) 
    self.y = random.randint(1,9)    

    field.table[self.x][self.y] = sign


  def growth(self, list, index, element):
    if list[index] != 0:
        return False
    else:
        field.table[self.x-v*b][self.y-v*c] = element


  def increase(self,p,b,c):                                               

        for v in range(p+1):
                self.growth(field.table,field.table.index((self.x-v*b,self.y-v*c)), self.sign) 
4

2 回答 2

1

You're confusing your indices in the two-dimensional list with values in the list. The statement

field.table.index((self.x-v*b, self.y-v*c))

looks for a value of (in your given error case) (1, 4) inside of the list field.table, which is of course not there. What you probably want is accessing field.table[1][4]. You could just pass the tuple as a variable to growth and use its elements as indices for the list, or pass field.table[self.x-v*b] as the list to growth and self.y-v*c as the index to access on that list.

Also, you are filling the list with "0"s but checking against 0 inside your growth function.

于 2012-12-01T16:05:47.570 回答
1

错误来自您的增加方法而不是您的增长方法。它发生在你打电话时table.index((self.x-v*b,self.y-v*c))。当您调用索引表时,我不清楚您要做什么,但是 index 方法返回列表中值的位置。例如:

>>> A = [0, 1, 5, 10]
>>> A.index(5)
2

table 似乎是 int 列表的列表,因此当您调用时,在 index.html中找不到table.index((1, 4))元组。(1, 4)也许你想要table[1][4]

更新:

我认为这就是你想要的:

self.growth(field.table, (self.x-v*b, self.y-v*c), self.sign)

并替换field.table[self.x-v*b][self.y-v*c]field.table[index[0]][index[1]]

(self.x-v*b, self.y-v*c)是你想要的索引,一旦你将它传递给增长,你需要使用它的参数名称来引用它。

于 2012-12-01T16:01:07.220 回答