2016-11-18 87 views
2

我有一个迭代遍历6x8元素数组的问题。不知何故,我得到一个无限循环。但我没有看到任何逻辑错误。在Python中迭代数组的列的无限循环

array=[[" "," "," "," "," "," "," "," "],[" "," "," "," "," "," "," "," "],[" "," "," "," "," "," "," "," "],[" "," "," "," "," "," "," "," "],[" "," "," "," "," "," "," "," "],[" "," "," "," "," "," "," "," "]] 

    i=1 
    j=1 
    while i<=6: 
     if "O" in array[i][j]: 
      i = i + 1 
      if i > 4: 
       print("Game over") 

其实我可以把一些输入到阵列。该数组表示像国际象棋场。我想每一次都要计算第1列中出现"O"的频率。如果出现的次数多于3次,则应打印"Game over"。但循环变得无限。

+0

尝试将换行i = i + 1放在if语句之外 – Skycc

回答

0

环路是无限的,因为i变量不递增,如果"O" in array[i][j]条件是False

此外,还有一种更好的方法来遍历数组在Python:

def check_column_cells(array, column): 
    counter = 0 

    for row in array: 
     if row[column] == "O": 
      counter += 1 
      if (counter > 3): 
       print("Game over") 
       return counter 

    return counter 

# Check the 2nd column (the indices start from 0) 
print(check_column_cells(array, 1)) 

如果你仍然想使用指标,应用增值业务:

def check_column_cells(array, column): 
    counter = 0 

    r = 0 
    while r < len(array): 
     if array[r][column] == "O": 
      counter += 1 
      if (counter > 3): 
       print("Game over") 
       return counter 
     r += 1 

    return counter 

# Check the 2nd column (the indices start from 0) 
print(check_column_cells(array, 1)) 

注意,我已经跳过为了清晰起见,进行安全检查。在上面的函数中,例如,您应该检查列索引是否在可用范围内。

0

您只增加如果。您需要增加i每个循环

我建议你在集合中使用循环。

Lists of lists

list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] 
for list in list_of_lists: 
    for x in list: 
     print x