2

所以我用numpy命名的高度生成一个随机列表......

heights = random.randint(10, size=random.randint(20))

我将此列表用于测试目的,但我有一个条件,我需要在每次生成时将第一个数字附加到列表中。基本上,对于生成的任何随机列表,我都需要始终创建 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:/

4

2 回答 2

3

你可以使用

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
于 2013-07-10T18:49:20.583 回答
0

You can also use np.concatenate() or np.hsatck():

heights = np.concatenate((heights, heights[0:1]))

or

heights = np.hstack((heights, heights[0:1]))
于 2013-07-10T18:56:06.767 回答