gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:26 24 4
gpt4 key购买 nike

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)

关于Python 使用 While 循环遍历二维列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35440500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com