替换2D列表中的元素



我的程序应该取我创建的表并替换这个符号的所有实例:"-"然后用一个数字来代替这个符号的数量"#"(炸弹)包围它。到目前为止,我得到的是:

import copy
# a function that takes a grid of # and -, where each hash (#) represents mine 
# and each dash (-) represents a mine-free spot
table=[
["-","-","-","#","#"],
["-","#","-","#","#"],
["-","-","#","-","-"],
["-","#","#","-","-"],
["-","-","-","-","-"]]
list2d= copy(table) #use copy to get the data from the list
for i in range(length(table)):
for k in range(length(table[0])):
if table[i][k]=='-':
table_count=0  # set the loop to start counting at 0
for a in(1, 2, 3):
for b in(1,2,3):
if(0 <= i+a < length(table) and 0<= k+b <length(table[0]) 
and table[i+a]):
table_count += 1
list2d[i][k]=str(table_count)
print(list2d)

一些问题:

  • copy是一个模块,而不是一个函数,所以不能调用它。但是既然你被要求用替换,并且没有提到新表,我不明白为什么你需要复制表。
  • length不是本机函数。应该是len
  • and table[i+a]是一种奇怪的状态。table[i+a]是表中的一行,并且是非空的,因此这始终是一个真条件。您应该检查单元格中是否有#符号,因此table[i+a][k+b] == "#".
  • list2d[i][k]=str(table_count)的缩进错误。这应该在内循环中发生,并且只有当单元格有连字符时才会发生。
  • (1,2,3)不是到达相邻行或列的正确偏移量。应该是(-1,0,1)

这是你的代码与这些问题纠正:

table=[
["-","-","-","#","#"],
["-","#","-","#","#"],
["-","-","#","-","-"],
["-","#","#","-","-"],
["-","-","-","-","-"]]
for i in range(len(table)):
for k in range(len(table[0])):
if table[i][k]=='-':
table_count=0
for a in(-1, 0, 1):
for b in(-1,0, 1):
if(0 <= i+a < len(table) and 0<= k+b <len(table[0]) 
and table[i+a][k+b] == "#"):
table_count += 1
table[i][k]=str(table_count)

如果输入表不应该被改变,但是必须创建一个新表,那么创建它为什么要做计数。您可以对所有这些使用列表推导式:

result = [
[
"#" if cell == "#" else str(sum(
0 <= i+a < len(table) and 0 <= k+b < len(row) 
and table[i+a][k+b] == "#"
for a in (-1, 0, 1) for b in (-1, 0, 1)
)) 
for k, cell in enumerate(row)
] for i, row in enumerate(table)
]

最新更新