简体   繁体   English

Python; 将位置保存在列表中以与另一个位置进行比较

[英]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.

相关问题 如何比较列表中的项目与另一个列表中的项目具有相同的值和位置? Python 2.7 - How to compare if an item in a list has the same value AND position as an item in another list? Python 2.7 Python:将鼠标 position 保存在一个列表中 - Python: saving mouse position in one list 如何将列表列表与 Python 中的另一个列表进行比较? - How to compare list of lists with another list in Python? Python中列表索引相对于另一个列表的位置 - Position of indices of a list with respect to another list in Python 如何根据相对列表 position 比较 python 列表中的对象? - How to compare objects in a python list based on their relative list position? 根据 Python 中另一个列表的位置选择列表的位置 - Pick position of a list based on the position of another list in Python 将列表列表保存到另一个列表列表中,但在 python 中进行了更改 - Saving list of lists into another list of list but with changes in python 由于python中的两个嵌套for循环,保存列表的正确位置是什么? - What is the correct position for saving a list as a result of two nested for loops in python? 从python中的列表中删除一个位置到另一个位置元素 - Deleting one position to another position elements from list in python 比较列表项与python中另一个列表的索引 - compare between item of list with index of another list in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM