我想生成一个包含 for 循环生成的所有元素的数组。我在 NumPy 手册或 stackoverflow 中没有找到任何相关或有用的内容。这是代码中有问题的部分。
import numpy as np
for i in range(0,26):
d = np.random.uniform(i,i+1.75)
empty = np.array([])
all = np.append(empty, d)
print all
我尝试了附加和连接,它们都只打印 25 个数组,但只存储到最后一个数组。
任何帮助将不胜感激。
最佳答案
@Moses 的答案效果很好,但你可以直接在 numpy 中实现这一点。 np.random.uniform
还采用大小参数。 See documentation 。因此,您的代码可以简化为:
all = np.random.uniform(0, 1.75, size=(26,))
all += np.arange(26)
这里的技巧是要认识到 np.random.uniform(0, 1.75) + 1
与 np.random.uniform(1, 2.75)
相同
第二行是考虑循环中的索引。结果将是:
array([ 0.82259558, 1.07737171, 3.56331306, 3.44506941,
5.36435903, 6.43062515, 7.4293016 , 8.62581585,
9.64664137, 10.11875821, 10.04800508, 12.03356491,
13.16818327, 14.12761814, 15.09009053, 15.96770449,
17.0981378 , 17.47152708, 18.15557107, 20.13834956,
21.22972932, 22.15797838, 22.97552168, 23.09385798,
24.17160732, 25.07440533])
这个解决方案可能有点难以理解,但当您想要进行更复杂的计算时,它是一个非常强大的模式。如果您不明白,请告诉我。而且,@Moses 的解决方案也是正确的!
关于python - 将 for 循环生成的元素追加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37897025/