Skip to main content
 首页 » 编程设计

python之将 for 循环生成的元素附加到数组中

2024年10月17日7soundcode

我想生成一个包含 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 

我已经尝试了 append 和 concatenate,它们都只打印 25 个数组但只存储到 all 最后一个。

任何帮助将不胜感激。

请您参考如下方法:

@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 的解决方案也是正确的!