在Python

时间:2016-11-18 13:13:23

标签: python

我有一个迭代6x8元素数组的问题。不知怎的,我得到了一个无限循环。但我没有看到任何合乎逻辑的错误。

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

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

我实际上可以将一些输入放入数组中。数组代表象棋场。我想在每一个回合计算{1}}在第1列中发生的频率。如果它出现的次数超过3次,则应打印"O"。但循环变得无限。

2 个答案:

答案 0 :(得分:0)

您只能在中增加 i 。您需要在每个循环增加 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

答案 1 :(得分:0)

循环是无限的,因为如果repo myRepo - 794b62a8b1cf4417c8320a261177b43bd5d8331e = @all 条件为i"O" in array[i][j]变量不会递增。

此外,还有一种更好的方法可以在Python中迭代数组:

False

如果您仍想使用索引,请应用增量操作:

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

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