2 回答
TA贡献1779条经验 获得超6个赞
一种方法是使用掩码用 中的值填充数组的无效条目,ls次数与 的排列相同ls。
但是,通过将这些排列的长度设置为 中无效条目的数量,可以使这更加健壮arr。那样我们也说明了这个情况len(ls) > (x == None).sum()。
可以使用itertools.permutations以下方法获得排列:
def fill_combs(x, fill, replace=None):
from itertools import permutations
m = x == replace
for i in permutations(fill, int(m.sum())):
x_ = x.copy()
x_[m] = np.array(i)
yield x_.astype(int)
示例运行:
arr = np.array([
[1, None, 3],
[9, 4, None],
])
ls = [9, 8]
list(fill_with_permut(arr, ls))
输出:
[array([[1, 9, 3],
[9, 4, 8]]),
array([[1, 8, 3],
[9, 4, 9]])]
或者更大的ls:
ls = [3,5,2]
list(fill_with_permut(arr, ls))
[array([[1, 3, 3],
[9, 4, 5]]),
array([[1, 3, 3],
[9, 4, 2]]),
array([[1, 5, 3],
[9, 4, 3]]),
array([[1, 5, 3],
[9, 4, 2]]),
array([[1, 2, 3],
[9, 4, 3]]),
array([[1, 2, 3],
[9, 4, 5]])]
TA贡献2080条经验 获得超4个赞
def update(arr, items):
count = 0
for i, x in enumerate(arr):
if None in x:
arr[i][x.index(None)] = items[count]
count += 1
return arr
import itertools
ls = [9, 8]
ls_ = list(itertools.permutations(ls))
for items in ls_:
arr = [[1, None, 3],
[9, 4, None]]
print (update(arr,items))
输出:
[[1, 9, 3], [9, 4, 8]]
[[1, 8, 3], [9, 4, 9]]
例子: ls = [9, 8, 15]
输出:
[[1, 9, 3], [9, 4, 8]]
[[1, 9, 3], [9, 4, 15]]
[[1, 8, 3], [9, 4, 9]]
[[1, 8, 3], [9, 4, 15]]
[[1, 15, 3], [9, 4, 9]]
[[1, 15, 3], [9, 4, 8]]
添加回答
举报