所以我生成一个带有 numpy 命名高度的随机列表...
heights = random.randint(10, size=random.randint(20))
我使用此列表进行测试,但我有一个条件,我需要在每次生成时将第一个数字 append 到列表中。基本上,我需要始终为生成的任何随机列表创建 2 个第一位数字。 因此,如果列表如下所示:
[1 2 2 5 5 6 7 7 7 9]
我需要它看起来像:
[1 2 2 5 5 6 7 7 7 9 1]
我尝试使用
heights.append(heights[0])
但是我收到一个错误。 这适用于列表,但不适用于 numpy:/
最佳答案
你可以使用
heights = np.random.randint(10, size=np.random.randint(1,21)); heights[-1] = heights[0]
预分配正确大小的数组比使用 np.append
、np.concatenate
或 np.hstack
快得多:
In [100]: %timeit heights = np.random.randint(10, size=np.random.randint(1,21)); heights[-1] = heights[0]
100000 loops, best of 3: 1.93 us per loop
In [99]: %timeit heights = np.random.randint(10, size=np.random.randint(1,20)); heights = np.append(heights, heights[0])
100000 loops, best of 3: 6.24 us per loop
In [104]: %timeit heights = np.random.randint(10, size=np.random.randint(1,20)); heights = np.concatenate((heights, heights[0:1]))
100000 loops, best of 3: 2.74 us per loop
In [105]: %timeit heights = np.random.randint(10, size=np.random.randint(1,20)); heights = np.hstack((heights, heights[0:1]))
100000 loops, best of 3: 7.31 us per loop
关于python - Numpy randint append ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17578566/