我有一个嵌套列表:
Table=[['','','','',''],
['','','','',''],
['','','','',''],
['','','','',''],
['','','','',''],
['','','','','']]
我在 Table
中随机放置了一些值,现在我想将其他内容放置在这些值的 2D 邻居中。例如:
Table=[['','','','',''],
['','','','',''],
['','','','',''],
['','','value','',''],
['','','','',''],
['','','','','']]
然后我想添加:
Table=[['','','','',''],
['','','','',''],
['','','1','',''],
['','1','value','1',''],
['','','1','',''],
['','','','','']]
下面是我的所有代码,我不知道为什么,但它会接受任何其他格式的代码,抱歉:/
def add_nukes():
pos=j.index('nuke')
if "nuke" not in j[0]:j[pos+1]='1'
if "nuke" not in j[-1]:
j[pos-1] = "1"
board[pos][i-1]="1"
board[i+1][pos]="1"
import random
size=150
if size%2==1:
size+=1
board = [[" "]*size for i in range(size)]
bombs = 25
all_cells = ["nuke"] * bombs + [" "] * (size - bombs)
random.shuffle(all_cells)
board = [all_cells[i:i+10] for i in range(0, size, 10)]
count=0
for j in board:
for i in range(len(j)):
count+=1
if "nuke" in j[i]:
add_nukes()
elif "nuke" in j[i]:
add_nukes()
for item in board:
print item
最佳答案
Table
中的任何值均由其 x
和 y
坐标唯一标识,即第二列中的元素 (x == 1
因为从 0 索引)并且第三行 (y == 2
) 是 Table[y][x] == Table[2][1]
.
任何单元格A
的四个直接邻居是与x
相距A
或y
的单元格> 距离A
一。如果 A
是 Table[y][x]
,则邻居为 [Table[y - 1][x], Table[y + 1][ x],表[y,x - 1],表[y,x + 1]]
。
关于python - 更改列表python中多个项目的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171781/