【发布时间】:2023-03-17 04:10:01
【问题描述】:
基本上我正在制作一个使用网格的基于 ascii 回合的游戏。我希望能够创建第二个网格或“层”,它保存有关该单元格的数据,并通过共享相同的索引值与第一个网格有直接关系。虽然我在以前的游戏版本中取得了一些工作成果,但我还是被卡住了,因为我不知道如何获取列表索引。
现在我发现我可以使用 inumerate() 函数获取索引。下面是一个练习 我试过的程序:
#some example lists
list = [[0, 2],[2, 3], [9,4], [5, 9]]
list2 =[[0, 0],[0, 0],[0, 0],[0, 0]]
# a for loop to iterate through all elements of the nested list
# using enumerate to to gain access to the list indices
for i, j in enumerate(list):
for ii, jj in enumerate(list):
# if statements below seemingly not working.
# jj is supposed to hold the contents of the current list cell
# also when the 'else' kicks in because jj didn't match anything
# throws an error index out of range
if jj == 0:
list2[i][ii] = 'A'
elif jj == 2:
list2[i][ii] = 'C'
else:
list2[i][ii] = 1
print(i, ii)
print(jj)
for i in list2:
print(i)
程序不工作,(我评论了我在上面的代码中遇到的错误),我想知道如何让它工作。非常感谢您的时间和耐心。
【问题讨论】:
-
for i, j in enumerate(list)我想你的意思是for i, j in enumerate(list2)。for ii, jj in enumerate(list)我想你的意思是for ii, jj in enumerate(j)。 -
我想你的意思是
for ii, jj in enumerate(j) -
@aecolley 我认为你和@inspectorG4dget 当你说我应该有
for ii, jj in enumerate(j)而不是(列表)时,但list2 是我希望根据第一个使用ii 的列表中的内容来改变的列表跟踪索引,所以我不知道为什么要枚举它。但是,是的,将第二个枚举更改为 (j) 使代码按预期工作,非常感谢你们! -
也许你想在外循环中枚举(list),在内循环中枚举(list2[i])?
-
另外,将变量命名为
list或file或dict是一个可怕的想法。避免命名变量与python数据结构共享名称
标签: python matrix iteration layer enumerate