您可以使用生成器函数查找每个有空字符串的位置,然后在迭代这些位置时deepcopy,生成一个新副本,下一个pos设置为x:def yield_pos(ls):
for ind, sub in enumerate(ls):
for ind2, ele in enumerate(sub):
if not ele:
yield ind, ind2
from copy import deepcopy
def step(ls):
ls_cp = deepcopy(ls)
for i,j in yield_pos(ls):
ls_cp[i][j] = "x"
yield ls_cp
ls_cp = deepcopy(ls_cp)
for cop in step(ls):
print(cop)
输出:
^{pr2}$
如果你每次只想要一个,而不是保持之前更新的x,那么我们只需要第一个逻辑:from copy import deepcopy
def yield_copy_x(ls):
for ind, sub in enumerate(ls):
for ind2, ele in enumerate(sub):
if not ele:
new = deepcopy(ls)
new[ind][ind2] = "x"
yield new
for cop in yield_copy_x(ls):
print(cop)
这给了你:[['x', 'a', 'b'], ['d', '', ''], ['', '', 'c']]
[['', 'a', 'b'], ['d', 'x', ''], ['', '', 'c']]
[['', 'a', 'b'], ['d', '', 'x'], ['', '', 'c']]
[['', 'a', 'b'], ['d', '', ''], ['x', '', 'c']]
[['', 'a', 'b'], ['d', '', ''], ['', 'x', 'c']]
如果您想要列表列表,您可以调用list:print(list(yield_copy_x(ls)))
这会给你:[[['x', 'a', 'b'], ['d', '', ''], ['', '', 'c']], [['', 'a', 'b'], ['d', 'x', ''], ['', '', 'c']], [['', 'a', 'b'], ['d', '', 'x'], ['', '', 'c']], [['', 'a', 'b'], ['d', '', ''], ['x', '', 'c']], [['', 'a', 'b'], ['d', '', ''], ['', 'x', 'c']]]
但是,除非您真的需要一次列出一个列表,否则您可以像firs示例一样迭代生成器函数。在