Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用字符串替换列表元素中的列表元素_Python_List_Ascii_Nested Lists - Fatal编程技术网

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

Python 用字符串替换列表元素中的列表元素,python,list,ascii,nested-lists,Python,List,Ascii,Nested Lists,所以我试图创建一个网格,可以用任何给定的符号替换它的单个“网格正方形”。网格工作正常,但它是由列表中的列表组成的 这是密码 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

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

这是密码

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]] = "@"

第一个将从左侧开始的所有“#”4个元素替换为“@” 第二个给出了以下错误

TypeError: 'int' object is not subscriptable

也许你在找这个:-

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] = "@"
将第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))
# # # # #
# # # # #
# # # # #
# # # @ #
# # # # #

但不会创建多个“@”。我只想替换特定的网格方格。这不是问题,无论您要替换哪个网格方格,只要在feild[I][0]中指定其行索引即可。如果我将其保留为I,这将替换整个网格。如果我改变,它会做一整行。我想,它会改变你网格中的特定元素。你的网格现在是49*1。所以,若要更改任何元素,必须将grid[][0]=设置为我已更改了代码。现在,您的网格大小将变为49*49。如果我这样做,我将得到一个完全由“@”组成的网格,我只想替换一个element@ayNONE我更新了答案,允许您单独更改任何行和列。
>>> size = 5
>>> c = '#'
>>> g = [size*[c] for i in range(size)]
>>> g[3][3] = '@'
>>> print('\n'.join(' '.join(row) for row in g))
# # # # #
# # # # #
# # # # #
# # # @ #
# # # # #