【问题标题】:python for loop in matrix to assign valuespython for循环在矩阵中分配值
【发布时间】:2017-03-01 17:00:42
【问题描述】:

我正在创建一个程序,该程序将创建一个网格,该程序将 除了您在输入处分配的矩阵数组的位置。

代码:

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

我在这方面还很陌生,所以感谢您的帮助

【问题讨论】:

  • 请在您的问题中包含代码作为格式化文本,并确保它是minimal reproducible example
  • 哈,看懂代码正常复制粘贴吗?

标签: python arrays for-loop matrix


【解决方案1】:

看起来您在第二个 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' 对象不可迭代

为什么你没有收到这个错误?

【讨论】:

  • 看看我的编辑。您甚至没有使用数组中的值。无论如何:以后不要使用重复的变量名;)
  • 非常感谢。我之前遇到过这个错误并修复了它。但这一次完全没有引起注意。 (在我的第一条评论中,我查看的是您的代码,而不是我的困惑所在的原始代码)
  • 太棒了。祝你的项目好运。
猜你喜欢
  • 2011-10-22
  • 1970-01-01
  • 2018-01-16
  • 2022-01-09
  • 1970-01-01
  • 2016-08-21
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多