[英]Python; Saving a position in a list to compare it with another
I tried to write a code that would add the position of a lists element to a new list.我试图编写一个代码,将列表元素的位置添加到新列表中。 When I later on would try to add a new element to the original list from a different object, the placement of the object would be compared with the list where I saved my previous element to make sure it doesn't get replaced.当我稍后尝试从不同的对象向原始列表添加新元素时,对象的位置将与我保存前一个元素的列表进行比较,以确保它不会被替换。
I'll paste the part of the code that is relevant to my question and it looks like this:我将粘贴与我的问题相关的代码部分,如下所示:
class gamefield:
def __init__(self):
self.table= [ [ "0" for i in range(10) ] for j in range(10) ]
class snake:
def __init__(self,sign):
self.sign = sign
self.x = random.randint(1,9)
self.y = random.randint(1,9)
self.bodylist = []
gamefield.table[self.x][self.y] = sign
self.bodylist.append(gamefield.table.index(sign))
field = gamefield()
snake1 = snake("+")
But I get the error: ""self.bodylist.append(gamefield.table.index(sign)) ValueError: '+' is not in list""但我收到错误:“”self.bodylist.append(gamefield.table.index(sign)) ValueError: '+' is not in list""
Shouldn't the '+" be in the list since I add it to gamefield.table just before I execute the code that causes the error? '+" 不应该在列表中,因为我在执行导致错误的代码之前将它添加到 gamefield.table 吗?
It's not in the list table
, it's in the list table[x]
.它不在列表table
,而是在列表table[x]
。 Your table is a list of lists, like so:您的表是一个列表列表,如下所示:
[
["0", ... ,"0"],
["0", ... ,"0"],
..
..
["0", ... ,"0"]
]
You probably should add the tuple (x,y)
to the body list您可能应该将元组(x,y)
到正文列表中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.