numpy.random.randint使用方法

https://docs.scipy.org/doc/numpy-1.16.1/reference/generated/numpy.random.randint.html

https://blog.csdn.net/tintinetmilou/article/details/79854725

https://www.programcreek.com/python/example/55590/numpy.random.randint

https://www.tutorialspoint.com/How-to-use-Python-Numpy-to-generate-Random-Numbers

https://segmentfault.com/a/1190000016097466

https://zhuanlan.zhihu.com/p/26889091

random.randint

numpy.random.randint可以创建范围是[low, high]之间的随机整数数组。

有以下几种参数:

  • low
  • high
  • size
  • dtype

来用例子学习吧!

指定Low+high

创建随机整数数组,返回[1, 10]之间的整数:

1
2
import numpy as np
np.random.randint(low = 1, high = 10, dtype=int)

结果只会是1~9。

不指定high

1
2
import numpy as np
np.random.randint(low = 1, dtype=int)

不指定high参数,结果只是0。也就是当我们不指定high参数时,low参数的值是数组里的最大范围。

1
2
import numpy as np
np.random.randint(low = 5, dtype=int)

这个的结果只是0~4。证明了low参数的值是数组里的最大范围。

指定size

1
2
3
4
import numpy as np
np.random.randint(low = 3, size = 1)

# 结果是 array([0/1/2])
1
2
3
4
import numpy as np
np.random.randint(low = 3, size = 2)

# 结果是 array([0~2, 0~2])
1
2
3
4
5
import numpy as np
np.random.randint(low = 5, size = (2, 2))

# 结果是 array([[0~4, 0~4],
# [0~4, 0~4]])

只指定size

1
2
3
>>> np.random.randint(2, size=10)

>>> array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
1
2
3
>>> np.random.randint(1, size=10)

>>> array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
1
2
3
4
>>> np.random.randint(5, size=(2, 4))

>>> array([[4, 0, 2, 1],
[3, 2, 2, 0]])

没有明确指定

1
2
3
4
5
>>> np.random.randint(1, 5)

# 返回[1, 5)之间随机的一个数字

>>> 0~4