首页 文章

TypeError:类型'int'的参数不可迭代

提问于
浏览
5

我运行程序时遇到此错误,我不明白为什么 . 错误发生在“如果1不在c:”中的行上

码:

matrix = [
    [0, 0, 0, 5, 0, 0, 0, 0, 6],
    [8, 0, 0, 0, 4, 7, 5, 0, 3],
    [0, 5, 0, 0, 0, 3, 0, 0, 0],
    [0, 7, 0, 8, 0, 0, 0, 0, 9],
    [0, 0, 0, 0, 1, 0, 0, 0, 0],
    [9, 0, 0, 0, 0, 4, 0, 2, 0],
    [0, 0, 0, 9, 0, 0, 0, 1, 0],
    [7, 0, 8, 3, 2, 0, 0, 0, 5],
    [3, 0, 0, 0, 0, 8, 0, 0, 0],
    ]
a = 1
while a:
     try:
        for c, row in enumerate(matrix):
            if 0 in row:
                print("Found 0 on row,", c, "index", row.index(0))
                if 1 not in c:
                    print ("t")
    except ValueError:
         break

我想知道的是我如何解决这个错误发生仍然让程序正确运行 .

提前致谢!

5 回答

  • 1

    这里 c 是索引而不是您要搜索的列表 . 由于您无法遍历整数,因此您将收到该错误 .

    >>> myList = ['a','b','c','d']
    >>> for c,element in enumerate(myList):
    ...     print c,element
    ... 
    0 a
    1 b
    2 c
    3 d
    

    你试图检查 1 是否在 c ,这是没有意义的

  • 2

    基于OP的评论 It should print "t" if there is a 0 in a row and there is not a 1 in the row.

    if 1 not in c 更改为 if 1 not in row

    for c, row in enumerate(matrix):
        if 0 in row:
            print("Found 0 on row,", c, "index", row.index(0))
            if 1 not in row: #change here
                print ("t")
    

    进一步澄清: row 变量本身包含一行,即 [0, 5, 0, 0, 0, 3, 0, 0, 0] . c 变量保存它所在行的索引 . 即,如果 row 持有矩阵中的第3行, c = 2 . 请记住 c 是从零开始的,即第一行是索引0,第二行是索引1等 .

  • 11

    c 是行号,所以它是 int . 所以数字不能是 in 其他数字 .

  • 0

    你试图迭代'c',它只是一个整数,保存你的行号 .

    如果连续0,则应打印“t”

    然后只需用行替换c就可以了:

    if 1 not in row:
    
  • 1

    我想你想 if 1 != c: - 测试 c 是否没有值 1 .

相关问题