你可以使用
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