Python 在检查列表单元格的内容时,如何从嵌套列表中获取列表索引?
基本上,我正在制作一个使用网格的基于ascii回合的游戏。我希望能够制作第二个网格或“层”,它保存有关该单元格的数据,并通过共享相同的索引值与第一个网格有直接关系。虽然我在以前的游戏构建中已经取得了一些工作成果,但即使是在这一过程中,我也陷入了困境,因为我不知道如何获取列表索引 现在我发现我可以通过使用inumerate()函数获得索引。下面是一个实践 我试过的程序:Python 在检查列表单元格的内容时,如何从嵌套列表中获取列表索引?,python,matrix,iteration,layer,enumerate,Python,Matrix,Iteration,Layer,Enumerate,基本上,我正在制作一个使用网格的基于ascii回合的游戏。我希望能够制作第二个网格或“层”,它保存有关该单元格的数据,并通过共享相同的索引值与第一个网格有直接关系。虽然我在以前的游戏构建中已经取得了一些工作成果,但即使是在这一过程中,我也陷入了困境,因为我不知道如何获取列表索引 现在我发现我可以通过使用inumerate()函数获得索引。下面是一个实践 我试过的程序: #some example lists list = [[0, 2],[2, 3], [9,4], [5, 9]
#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)
这个程序不工作,(我对上面代码中的错误进行了评论),我想知道如何让它工作。非常感谢您的时间和耐心
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#some example myLists
myList = [[0, 2],[2, 3], [9,4], [5, 9]]
myList2 =[[0, 0],[0, 0],[0, 0],[0, 0]]
for index0, value0 in enumerate(myList):
for index1, value1 in enumerate(value0):
if value1 == 0:
myList2[index0][index1] = 'A'
elif value1 == 2:
myList2[index0][index1] = 'C'
else:
myList2[index0][index1] = 'else'
print myList2
希望有帮助。因为两个列表中的每个单元格都将被访问,而且每个单元格的索引都直接映射(列表中的0映射到列表2中的0),所以当前索引是隐含的,可以使用列表理解
grid = [[0, 2], [2, 3], [9, 4], [5, 9]]
mapping = {0: 'A', 2: 'C'}
grid2 = [[mapping.get(cell, 1) for cell in row] for row in grid]
对于枚举(列表)中的i,j,我想你指的是枚举(列表2)中的i,j的
。我想你的意思是,我想你的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我,但是列表2是我希望根据第一个列表中的内容来改变的列表,使用ii来跟踪索引,所以我不知道为什么我要列举它。但是是的,将第二个枚举更改为(j)使代码按预期工作,非常感谢!也许你想在外循环中枚举(list),而在内循环中枚举(list2[i])?另外,给变量命名list
或文件或dict
也是个糟糕的主意。避免命名变量以与python数据结构共享名称