Home > OS >  how to loop through nested array with None type
how to loop through nested array with None type

Time:08-05

I'm trying to go through each row of my field and then each column within the row, but my field is made of None for the empty spaces that I need. My code gives a type error NoneType object is unsubscriptable, so how can I go about skipping the Nones in my field?

field = [ [['PEASH', 5], None, None, None, None, None, ['ZOMB', 15]],
          [['PEASH', 5], None, None, None, None, None, ['ZOMB', 15]],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None] ]

num_rows=len(field)
num_columns=len(field[0])

lane = 0
row_counter = -1
column_counter = -1
for row in range(num_rows):
    row_counter  = 1
    print('rowcounter is at',row_counter)
    print(row)
    for column in range(num_columns): #for each column, 
        column_counter  = 1

        element = field[row][column] 
        print(element) #now element will be ['peash',15]
        if element[0] == 'PEASH':
            print('yes there is a peashooter in',row_counter,column_counter)
            

CodePudding user response:

simply change

if element[0] == 'PEASH':
    print('yes there is a peashooter in',row_counter,column_counter)

to

if element is not None:
    if element[0] == 'PEASH':
        print('yes there is a peashooter in',row_counter,column_counter)

CodePudding user response:

This should do it:

if element and element[0] == 'PEASH'

CodePudding user response:

Explanations are in the comments.

field = [ [['PEASH', 5], None, None, None, None, None, ['ZOMB', 15]],
          [['PEASH', 5], None, None, None, None, None, ['ZOMB', 15]],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None] ]

# Python, as a high-level language, can perform iteration in the follow way
for i, row in enumerate(field): # E.g. first row => i = 0; row = [['PEASH', 5], None, None, None, None, None, ['ZOMB', 15]]
    for j, element in enumerate(row):
        print(element) # I don't know what's the use of this, but just to keep it as-is in your code
        if element is None:
            continue # Skip ahead to next element
        if element[0] == 'PEASH':
            print('yes there is a peashooter in',i,j)

CodePudding user response:

Try checking if element is equal to "None":

if element[0] == "PEASH" and element is not None:
    print('yes there is a peashooter in',row_counter,column_counter)
    
  • Related