Python使用While循环迭代2D列表

时间:2016-02-16 18:37:06

标签: python

grid = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
cages = [[9, 3, 0, 5, 6], [7, 2, 1, 2], [10, 3, 3, 8, 13], [14, 4, 4, 9, 14, 19], [3, 1, 7], [8, 3, 10, 11, 16], [13, 4, 12, 17, 21, 22], [5, 2, 15, 20], [6, 3, 18, 23, 24]]

noCages = 9
total = 0
i = 0
index = 2
while i < noCages:
   while index < len(i):
      total = total + grid[index/5][index%5]
      print grid[index/5][index%5]
      index += 1
   print total
   i += 1
   total = 0

我试图使用while循环遍历笼子列表,并将第二个元素带到每个嵌套列表中的最后一个元素。我然后将这些值添加到总计中,我想对所有嵌套列表执行此操作。我在使用while循环迭代笼子列表时遇到了麻烦。我怎样才能更好地实现这一点。 (它也说len(i)是一个int并且没有长度,这是有道理的。但是,我不知道如何使用它。

1 个答案:

答案 0 :(得分:1)

如果您使用for循环,您将从嵌套列表(for cage in cages)中一次获得一个列表,然后您可以使用另一个列表来读取单个值。 [1:]说跳过第一个元素。

total = 0
for cage in cages:
    for value in cage[1:]:
        total += value
print(total)
相关问题