python - 如何生成这个特定的列表列表
问题描述
我有一个复杂的问题。我正在尝试创建一个函数,该函数接受 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
解决方案
您可以获得要变异的索引列表,然后使用它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]]
推荐阅读
- python - 从“deeppavlov.core.commands.train”导入“train model from_config”时出错
- python - 使用 Flask 返回 Html 属性
- ruby-on-rails - 如何使用下拉列表从独立页面设置 id?或者我如何保存belongs_to、has_many 值?
- javascript - 如何在 vue.js 组件中使用导入的 javascript 库构造函数?
- android - 在 ScrollView 中使用可扩展的 textView 垂直居中 ConstraintLayout(滚动/居中问题)
- android - 在 Firebase Android 中读写
- r - 基于R中多个其他变量中的值有条件地替换变量中的值
- wear-os - Java wear os Scroll WearableRecyclerView by 数码冠
- spring - 为什么 Spring Web Flux 调度处理程序有界的弹性调度
- reactjs - 浅拷贝一个 React 组件,并在 Enzyme 中提供存储