我是python新手,我知道必须有更好的方法来实现这一点,尤其是使用numpy,而且不需要附加到数组。在python中有没有一种更简洁的方法来完成类似的操作?在
def create_uniform_grid(low, high, bins=(10, 10)):
"""Define a uniformly-spaced grid that can be used to discretize a space.
Parameters
----------
low : array_like
Lower bounds for each dimension of the continuous space.
high : array_like
Upper bounds for each dimension of the continuous space.
bins : tuple
Number of bins along each corresponding dimension.
Returns
-------
grid : list of array_like
A list of arrays containing split points for each dimension.
"""
range1 = high[0] - low[0]
range2 = high[1] - low[1]
steps1 = range1 / bins[0]
steps2 = range2 / bins[1]
arr1 = []
arr2 = []
for i in range(0, bins[0] - 1):
if(i == 0):
arr1.append(low[0] + steps1)
arr2.append(low[1] + steps2)
else:
arr1.append(round((arr1[i - 1] + steps1), 1))
arr2.append(arr2[i - 1] + steps2)
return [arr1, arr2]
low = [-1.0, -5.0]
high = [1.0, 5.0]
create_uniform_grid(low, high)
# [[-0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8],
# [-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0]]
np.ogrid
与您的函数类似。区别:1)它将保留端点;2)它将创建一列和一行,因此其输出为“广播就绪”:也许
numpy.meshgrid
就是你想要的。在下面是一个创建网格并对其进行数学运算的示例:
参考:
相关问题 更多 >
编程相关推荐