我想在 python 中生成一组整数数组和整数值之间的映射,例如 n=2
(数组的大小)和 m=2
(数组项范围),我想要:
{
0: [0, 0, 0],
1: [0, 0, 1],
2: [0, 1, 1],
3: [1, 0, 0],
...
7: [1, 1, 1]
}
实现此目的的一种方法是使用 itertools.product
并执行以下操作:
from itertools import product
import numpy as np
n = 2
m = 3
a = list(product(np.arange(n), repeat=3))
a = list(map(lambda l: list(l), a))
b = dict(zip(np.arange(len(a)), a))
和b
将是:
{0: [0, 0, 0], 1: [0, 0, 1], 2: [0, 1, 0], 3: [0, 1, 1], 4: [1, 0, 0], 5: [1, 0, 1], 6: [1, 1, 0], 7: [1, 1, 1]}
我可以得到提到的映射,例如
>>> b[1]
[0, 0, 1]
但是,就我而言,n=8
和 m=16
并存储这样的字典(8**16
条目!)将需要超过 100 Gb。我想知道是否有一种懒惰的方法来生成 b 的每个索引,每次我想访问它而不生成整个字典?
最佳答案
您可以创建一个函数而不是完整的 map 。您的输出实际上是大小为 m 的数组,表示输入 a 的 n 级表示法的值。如果你想制作一个 map ,如果键不存在,只需将函数的结果保存在 map 中即可。
def f(a, n, m):
res = []
while a != 0:
res = [a % n] + res
a //= n
m -= 1
while m != 0:
res = [0] + res
m -= 1
return res
关于python - 整数和数组排列之间的惰性映射,无需生成所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70436145/