python列表返回固定元素位置_在Python中,如何在一个元素改变位置的情况下返回嵌套列表的列表?...

您可以使用生成器函数查找每个有空字符串的位置,然后在迭代这些位置时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示例一样迭代生成器函数。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值