简体   繁体   English

如何循环使用 None 类型的嵌套数组

[英]how to loop through nested array with None type

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.我正在尝试 go 遍历我的字段的每一行,然后是行中的每一列,但是对于我需要的空白空间,我的字段由 None 组成。 My code gives a type error NoneType object is unsubscriptable, so how can I go about skipping the Nones in my field?我的代码给出了一个类型错误 NoneType object 是不可订阅的,那么我怎么能 go 关于跳过我的领域中的无?

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)
            

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)

This should do it:这应该这样做:

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

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)

Try checking if element is equal to "None":尝试检查element是否等于“无”:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM