Skip to main content
 首页 » 编程设计

Python 使用 While 循环遍历二维列表

2025年05月04日9傻小

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 循环遍历 cages 列表并获取每个嵌套列表中的第二个元素到最后一个元素。然后我将这些值加到总计中,我想对所有嵌套列表都这样做。我在使用 while 循环遍历 cages 列表时遇到问题。我怎样才能更好地实现这一点。 (它还说 len(i) 是一个 int 并且没有长度,这是有道理的。但是,我不知道如何使用它。

请您参考如下方法:

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

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