【问题标题】:Python using While loops to iterate through a 2D listPython 使用 While 循环遍历 2D 列表
【发布时间】:2016-02-16 18:37:06
【问题描述】:
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 并且没有长度,这是有道理的。但是,我不知道如何使用它。

【问题讨论】:

  • 你的预期输出是什么?
  • 不确定您使用的是 Python 2 还是 3,但在 Python 3 中您不能使用 [index/5] 作为列表索引,因为这将返回一个浮点数。如果你想得到cages[0][1 to 4]的总和,你可以使用sum(cages[0][1:5])。使用 sum 函数,您可以添加您想要的列表的任何部分,而无需迭代它们。
  • 为什么是while 循环? for 不是更适合您的用例吗?

标签: python


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-03-05
    • 1970-01-01
    • 2021-10-24
    • 2018-10-26
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    相关资源
    最近更新 更多