0

リストのリスト内で特定のリストを検索するにはどうすればよいですか?

他の多くのリストを含むリスト grid_list があり、grid_list を検索してこれらの 1 つを見つけたいとします。具体的にはどうすればこれを行うことができますか? これは私がうまくいくと思うコードですが、そうではありません:

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)])

このコードは、他の多くのリストを含むリストを設定し (スペース関数)、リスト内のリストの 1 つ (grid_list) を変更して、そのリストに食品が含まれていることを表します。

ただし、この作業の代わりに、[2,1,0,0,0] がリストにない、またはコードが提供する他のグリッド値がないという値エラーが発生します (この状況では、2 と 1 を任意の正の整数に置き換えることができます) )。誰かがこれを変更して正しく検索する方法を説明してもらえますか?

4

3 に答える 3