用字符串替换列表元素中的列表元素

2024-06-16 17:09:20 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试图创建一个网格,可以用任何给定的符号来替换它的单个“网格正方形”。网格工作正常,但它是由列表中的列表组成的。你知道吗

这是密码

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

Tags: ofin网格列表forsizeisrange
2条回答

#作为网格,第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))
# # # # #
# # # # #
# # # # #
# # # @ #
# # # # #

可能你在找这个:-

size = 49
feild = []
for i in range(size):
    feild.append([])
for i in range(size):
    map(feild[i].append, ["#" for _ in xrange(size)])
i = 4
feild[i][0] = "@"

相关问题 更多 >