创建一个大小为x的向量,其中两个数字随机分割

问题描述 投票:0回答:1

我目前需要创建一个大小为x的数组,并用随机分割的1s或-1s填充它。我可以轻松地创建一个数组并用randint填充它,但问题是我不想在我的数组中使用0。

我也有一个精确的数组长度数,所以我需要确保我总共有100或1000个整数。

如果有人知道如何顺利​​解决这个问题,我将非常感激。

谢谢

python arrays random
1个回答
0
投票

正如@roganjosh在评论中提到的那样你可以使用choice,一种替代方法是使用randint并改变边界,如下所示:

import numpy as np

a = (2 * np.random.randint(low=0, high=2, size=10)) - 1
print(a)

产量

[ 1  1  1 -1 -1 -1  1 -1  1  1]

基准

import timeit

print(timeit.timeit('a = (2 * np.random.randint(low=0, high=2, size=1000)) - 1', setup='import numpy as np', number=10000))
print(timeit.timeit('a = np.random.choice([-1, 1], 1000)', setup='import numpy as np', number=10000))

产量

0.10986099799993099
0.18005346000063582
© www.soinside.com 2019 - 2024. All rights reserved.