首页 > 解决方案 > 如何生成这个特定的列表列表

问题描述

我有一个复杂的问题。我正在尝试创建一个函数,该函数接受 0 和 1 列表并返回列表列表。如果我只是举一个例子,那是最简单的

输入

[0,0,0,1,0,1]

输出

[[0,0,0,0,0,0,0],[1,0,0,0,1,0,0],[1,0,0,0,1,0,1],[1,0,0,0,0,0,1],[1,0,0,0,0,0,0]]

另一个例子

输入

[1,0,1]

输出

[[0,0,0,0],[1,1,0,0],[1,0,0,1],[1,1,0,1],[1,0,0,0]]

我现在有一个解决方案,我首先生成所有组合,然后过滤掉不允许的组合。但这需要大量内存,所以我正在寻找更好的解决方案。

def func(input):
    A = list(itertools.product(range(2), repeat=int(len(input)+1)))

    # Filters out all the lists which have first element equal to 0 
    #  and 1s anywhere else 
    A = [item for item in A if not (item[0] == 0 \
                    and sum(item) >= 1 or item[A.index(item)+1] == 1) ]

    # Filter out all lists which has 1s at places the input does not have
    A = [item for item in action_space if not \
                    sum(np.bitwise_and(np.bitwise_xor(item[1:], \
                    self.adj_mat[node.get_node_nr()]),item[1:])) > 0]

    return A

标签: pythonlist

解决方案


您可以获得要变异的索引列表,然后使用它itertools.product来生成所有可能的变化。

from itertools import product

def func(l):
    indicies = [i for i, x in enumerate(l, start=1) if x]
    prod = product([0, 1], repeat=len(indicies))
    yield [0] * (len(l) + 1)
    for variation in prod:
        temp = [1, *l]
        for index, value in zip(indicies, variation):
            temp[index] = value
        yield temp

print(list(func([0,0,0,1,0,1])))
# [[0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 1, 0, 1]]
print(list(func([1,0,1])))
# [[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 1], [1, 1, 0, 0], [1, 1, 0, 1]]

推荐阅读