python for matrix in matrix to assign values

时间:2017-03-01 17:00:43

标签: python arrays for-loop matrix

我正在创建一个程序,它将创建一个网格,程序将会 通过您在输入处指定的矩阵数组来确定其位置。

代码:

def onbekende_naam(hoogtes):
    print(hoogtes)
    i = 0
    j = 0
    pos1 = set()

    for hoogtes_subs in hoogtes:
        j = 0
        for hoogtes in hoogtes:
            print("i = " + str(i))
            print("j = " + str(j))
            pos1.add((i, j))
            print pos1
            j += 1
        i += 1
        #pos1.add((i, j))

    return pos1

#verwerking
print (onbekende_naam(hoogtes)) 

输入:

4 4
1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 7
12 1

输出:

[['1', '2', '3', '4'], ['5', '6', '7', '8'], ['9', '1', '2', '3'], ['4', '5', '6', '7']]
i = 0
j = 0
set([(0, 0)])
i = 0
j = 1
set([(0, 1), (0, 0)])
i = 0
j = 2
set([(0, 1), (0, 0), (0, 2)])
i = 0
j = 3
set([(0, 1), (0, 3), (0, 0), (0, 2)])
i = 1
j = 0
set([(0, 1), (0, 3), (0, 0), (0, 2), (1, 0)])
i = 1
j = 1
set([(0, 1), (0, 0), (0, 2), (1, 0), (0, 3), (1, 1)])
i = 1
j = 2
set([(0, 1), (1, 2), (0, 0), (0, 2), (1, 0), (0, 3), (1, 1)])
i = 1
j = 3
set([(0, 1), (1, 2), (0, 0), (0, 2), (1, 3), (1, 0), (0, 3), (1, 1)])
i = 2
j = 0
set([(0, 1), (1, 2), (0, 0), (0, 2), (2, 0), (1, 3), (1, 0), (0, 3), (1, 1)])
i = 3
j = 0
set([(0, 1), (1, 2), (0, 0), (3, 0), (0, 2), (2, 0), (1, 3), (1, 0), (0, 3), (1, 1)])
set([(0, 1), (1, 2), (0, 0), (3, 0), (0, 2), (2, 0), (1, 3), (1, 0), (0, 3), (1, 1)])

正如您所看到的,当i值大于2

时,它会停止递增j

我是相当新的,所以感谢帮助

1 个答案:

答案 0 :(得分:0)

看起来您在第二个for循环中使用相同的名称。你可以尝试改变这种方法吗?

def onbekende_naam(hoogtes):
    print(hoogtes)
    i = 0
    j = 0
    pos1 = set()

    for hoogtes_subs in hoogtes:
        j = 0
        for another_name_hoogtes in hoogtes:
            print("i = " + str(i))
            print("j = " + str(j))
            pos1.add((i, j))
            print pos1
            j += 1
        i += 1
        #pos1.add((i, j))

    return pos1

#verwerking
print (onbekende_naam(hoogtes)) 

另外:当我运行原始代码时,我收到以下错误:

  

TypeError:'int'对象不可迭代

为什么没有收到此错误?