在Python中,如何返回嵌套列表列表,其中一个元素更改位置?

时间:2016-04-04 20:18:33

标签: python list nested

例如,假设我有一个列表,例如:

ls = [['','a','b'],
      ['d','',''],
      ['','','c']]

我可以添加另一个项目,一次一个地在空插槽中添加'x'并创建所有结果的列表吗?

澄清一下,由于有5个空格,我想要5个新的ls副本,每个副本只有一个添加'x',每次都在不同的位置。

2 个答案:

答案 0 :(得分:4)

您可以使用生成器函数查找空字符串的每个位置,然后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)

输出:

[['x', 'a', 'b'], ['d', '', ''], ['', '', 'c']]
[['x', 'a', 'b'], ['d', 'x', ''], ['', '', 'c']]
[['x', 'a', 'b'], ['d', 'x', 'x'], ['', '', 'c']]
[['x', 'a', 'b'], ['d', 'x', 'x'], ['x', '', 'c']]
[['x', 'a', 'b'], ['d', 'x', 'x'], ['x', 'x', 'c']]

如果你想每次只保留一次更新的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']]

如果您想要一个列表列表,您只需拨打列表:

 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']]]

但除非您确实需要一次列表,否则您可以像第一个例子一样迭代生成器函数。

答案 1 :(得分:0)

试试这个:

import copy

ls = [['','a','b'],
      ['d','',''],
      ['','','c']]

def get_index():
    # Function to get the index which match the criteria.
    for index0, list0 in enumerate(ls):
        for index1, item in enumerate(list0):
            if item == '':
                # The criteria matches, yield the indexes.
                yield index0, index1

def edit_ls():
    final_list = []
    for index0, index1 in get_index():
        # Copy the original list.
        new_ls = copy.deepcopy(ls)
        # at the index set value.
        new_ls[index0][index1] = 'x'
        # Append the list to final result.
        final_list.append(new_ls)
    return final_list