gpt4 book ai didi

python - 构建所有可能数字列表的更智能方法

转载 作者:太空宇宙 更新时间:2023-11-04 08:41:16 24 4
gpt4 key购买 nike

我必须按照给定的步长(目前为 1/3)构建一个 3x2 值组合列表,其中包含 0.0 到 1.0 之间的所有可能值。

输出应该是 [ [[v1, v2], [v3, v4], [v5, v6]], ... ] 其中每个 v 是一个介于 0.0 和 1.0 之间的值,例如:

[ [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]],
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.33]],
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.66]],
[[0.0, 0.0], [0.0, 0.0], [0.0, 1.0]],
[[0.0, 0.0], [0.0, 0.0], [0.33, 0.0]],
[[0.0, 0.0], [0.0, 0.0], [0.33, 0.33]],
...,
[[1.0, 1.0], [1.0, 1.0], [1.0, 1.0]] ]

到目前为止我有:

step = 1.0/3.0
lexica = []
for num1 in numpy.arange(0.0, 1.0, step):
for num2 in numpy.arange(0.0, 1.0, step):
for num3 in numpy.arange(0.0, 1.0, step):
for num4 in numpy.arange(0.0, 1.0, step):
for num5 in numpy.arange(0.0, 1.0, step):
for num6 in numpy.arange(0.0, 1.0, step):
lexica.append([[num1, num2],[num3, num4],[num5, num6]])

这不会获得 1.0 的最高值,并且知道 Python 必须有更好的编写方法。

最佳答案

您可以使用 numpy.mgrid 并对其进行操作以获得您想要的输出

np.mgrid[0:1:step, 0:1:step, 0:1:step, 0:1:step, 0:1:step, 0:1:step].T.reshape(-1, 3, 2)

编辑:

修复端点的更可扩展的方法:

def myMesh(nSteps, shape = (3, 2)):
c = np.prod(shape)
x = np.linspace(0, 1, nSteps + 1)
return np.array(np.meshgrid(*(x,)*c)).T.reshape((-1, ) + shape)

myMesh(3)

array([[[ 0. , 0. ],
[ 0. , 0. ],
[ 0. , 0. ]],

[[ 0. , 0.33333333],
[ 0. , 0. ],
[ 0. , 0. ]],

[[ 0. , 0.66666667],
[ 0. , 0. ],
[ 0. , 0. ]],

...,
[[ 1. , 0.33333333],
[ 1. , 1. ],
[ 1. , 1. ]],

[[ 1. , 0.66666667],
[ 1. , 1. ],
[ 1. , 1. ]],

[[ 1. , 1. ],
[ 1. , 1. ],
[ 1. , 1. ]]])

关于python - 构建所有可能数字列表的更智能方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44648364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com