TypeError: list indices must be integers, not list. How to fix?

前端 未结 2 815
轻奢々
轻奢々 2020-12-20 19:36

There\'s the code with the TypeError in it. \"list indices must be integers, not list\", though they are integers. I\'d appreciate you helping me figure out what\'s wrong.

相关标签:
2条回答
  • 2020-12-20 20:12
    for i in lines:
        for j in lines:
    

    i and j iterate over the elements of lines, not the indices. That means i and j are always lists, entire lines of numbers.

    If you want to go over the indices (usually you don't, but it may be the best option here), you want

    for i in range(len(lines)):
        for j in range(len(lines[i])):
    

    This is awkward by design, as the Python designers want people to default to iterating over the elements of a sequence.

    Also, note that your loop tries to access elements of lines before the first row and before the first column. Perhaps you want to start your loops on the second row and column.

    0 讨论(0)
  • 2020-12-20 20:14

    i and j are not indices; they are values from the lines list. Python for loops are for-each constructs.

    Use:

    for i, line in enumerate(lines):
        for j, value in enumerate(line):
            T[i][j] = value + max(T[i][j - 1 % len(T[i])] + T[i - 1 % len(T)][j])
    

    where the % len() calculations 'wrap around' to the last entry in T or T[i] when i and / or j are 0. The enumerate() function adds indices to the loop.

    This does assume you already pre-built a nested list of lists structure in T.

    0 讨论(0)
提交回复
热议问题