python - 更改列表python中多个项目的值

标签 python python-2.7 list

我有一个嵌套列表:

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 中的任何值均由其 xy 坐标唯一标识,即第二列中的元素 (x == 1 因为从 0 索引)并且第三行 (y == 2) 是 Table[y][x] == Table[2][1].

任何单元格A的四个直接邻居是与x相距Ay的单元格> 距离A一。如果 ATable[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/

相关文章:

python - 在python中将文件作为列表读取

python - 有没有一种方法可以调整 NumPy 数组的大小/形状,从而保留每行的 sum()

在 Ubuntu 18.04 中找不到 Python google.appengine.api

javascript - Python/Javascript -- 整数按位异或问题

python - 在 python 中对一个大文件进行异或运算

python - python使用正则表达式去除括号中的内容

c++ - 断言失败 : calling a list's node deconstructor

python - Pandas:Groupby 并使用剩余的列名和值创建字典

python-2.7 - DEAP 工具箱 : to consider different types and ranges of genes in mutation and crossover operators

list - 如何在一列中从列表中的所有对象获取相同的属性