如何在列表列表中搜索特定列表,如此具体:
假设我有一个包含许多其他列表的列表 grid_list,我想通过 grid_list 搜索以找到其中一个,具体我该怎么做?这是我认为应该有效但无效的代码:
import sys #sys has been imported to take in user input
import random #random has been imported to generate random numbers to store the ants food in in the grid
#grid list is a generated list used to store grid values
grid_list = []
grid_size=0 #grid size is a variable that is assigned a value in function space and used in other functions, has default value of zero
ant_position="" #ants current position in grid used in more than one function
food_location="" #foods position in grid used in more than one function
#function for setting up a grid
def space():
print("please enter the size of the square grid you want")
#grid size is assigned by user input
global grid_size
grid_size = int(sys.stdin.readline())
#embedded for loops to set up a list that stores grid points
for count in range(0,grid_size):
x_number= count+1 #x number is the x number of the cell in the grid
for count in range(0,grid_size):
y_number= count+1 # y number is the y number of the cell in the grid
grid_list.append([x_number,y_number,0,0,0]) #this stores a list within a list, so the first two values of the second list represent the co-ordinates of the cell the last three represent pheromone, food location, ant location (both food and ant location take value of one if either are in there)
def locations():
global food_location
food_location_x = (random.randint(1,grid_size)) #gives the x value of the cell the food is stored in
food_location_y = (random.randint(1,grid_size)) #gives the y value of the cell the food is stored in
food_location = [food_location_x,food_location_y,0,0,0] #gives the full location of the food and will use this to in other functions to reference the grid list
for count in range(0,4):
grid_list[[grid_list.index([food_location])][count]] = [food_location_x,food_location_y,0,1,0]
print(grid_list[grid_list.index(food_location)])
此代码设置一个包含许多其他列表的列表(空间函数),然后更改列表中的一个列表(grid_list)以表示它包含食物。
然而,我得到一个值错误,而不是这个工作,说 [2,1,0,0,0] 不在列表中或代码给出的任何其他网格值(在这种情况下,2 和 1 可以用任何正整数替换)。有人可以向我解释一下如何更改它以便正确搜索吗?