How do I get list indices from nested lists while checking the contents of the list cell?


basically I'm making an ascii turn based game that uses a grid. I want to be able to make a second grid or 'layer' that holds data about that cell and has a direct relationship to the first grid through sharing the same index values. While i have achieved some working results in a previous build of my game, even in that i got stuck because I couldn't figure out how to get the list indices.

Now I've found out that I can get the indices by using the inumerate() function. Below is a practice program I tried:

    #some example lists
    list = [[0, 2],[2, 3], [9,4], [5, 9]]
    list2 =[[0, 0],[0, 0],[0, 0],[0, 0]]

    # a for loop to iterate through all elements of the nested list
    # using enumerate to to gain access to the list indices

    for i, j in enumerate(list):
        for ii, jj in enumerate(list):

            # if statements below seemingly not working.
            # jj is supposed to hold the contents of the current list cell
            # also when the 'else' kicks in because jj didn't match anything
            # throws an error index out of range

            if jj == 0:
                list2[i][ii] = 'A'
            elif jj == 2:
                list2[i][ii] = 'C'
                list2[i][ii] = 1
        print(i, ii)
    for i in list2:

The program doesn't work, (I commented about the errors I get in the code above) and I'd like to know how I can get it to work. Thanks a lot for your time and patience.

  1. DO NOT use name of built-in function as name of your variable.
  2. Use meaningful variable name instead of meaningless ones, like ii, jj, which will make your code hard to read

I think you want to assign new values to the second list according to values of first list. Try this:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

#some example myLists
myList = [[0, 2],[2, 3], [9,4], [5, 9]]
myList2 =[[0, 0],[0, 0],[0, 0],[0, 0]]

for index0, value0 in enumerate(myList):

    for index1, value1 in enumerate(value0):

        if value1 == 0:
            myList2[index0][index1] = 'A'
        elif value1 == 2:
            myList2[index0][index1] = 'C'
            myList2[index0][index1] = 'else'

print myList2

Hope it helps.