因此,我试图创建一个可以用任何给定符号替换其单独的“网格正方形”的网格。网格工作正常,但它由列表中的列表组成。

这是代码

size = 49
feild = []
for i in range(size):
    feild.append([])
for i in range(size):
    feild[i].append("#")
feild[4][4] = "@" #This is one of the methods of replacing that I have tried
for i in range(size):
    p_feild = str(feild)
    p_feild2 = p_feild.replace("[", "")
    p_feild3 = p_feild2.replace("]", "")
    p_feild4 = p_feild3.replace(",", "")
    p_feild5 = p_feild4.replace("'", "")
    print(p_feild5)


如您所见,这是我尝试替换元素的一种方式,我也尝试过:

feild[4[4]] = "@"




feild[4] = "@"


第一个用“ @”替换左起的所有“#” 4个元素
第二个给出以下错误

TypeError: 'int' object is not subscriptable

最佳答案

在第3行第3列的#网格中用@代替:

>>> size = 5
>>> c = '#'
>>> g = [size*[c] for i in range(size)]
>>> g[3][3] = '@'
>>> print('\n'.join(' '.join(row) for row in g))
# # # # #
# # # # #
# # # # #
# # # @ #
# # # # #

关于python - 用字符串替换list元素内的list元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33603729/

10-13 02:40
查看更多