Python-arange()、reshape()和random.seed()的用法

1. arange()函数和reshape()函数

arange()用于生成一维数组,通过指定开始值、终值和步长来创建表示等差数列的一维数组,返回给定间隔内的均匀间隔值,注意得到的结果数组不包含终值。

reshape()将一维数组转换为多维数组

(py3.6) E:\PYTHON>python
Python 3.6.13 |Anaconda, Inc.| (default, Mar 16 2021, 11:37:27) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> b = np.arange(1, 5)
>>> b
array([1, 2, 3, 4])
>>> c = np.arange(2, 10, 2)
>>> c
array([2, 4, 6, 8])
>>> d = np.arange(8).reshape((2, 4))
>>> d
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
>>> e = np.arange(60).reshape((3, 4, 5))
>>> e
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]],

       [[20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34],
        [35, 36, 37, 38, 39]],

       [[40, 41, 42, 43, 44],
        [45, 46, 47, 48, 49],
        [50, 51, 52, 53, 54],
        [55, 56, 57, 58, 59]]])
>>> f = np.random.randint(1, 8, size=(3, 4, 5))
>>> f
array([[[2, 2, 1, 4, 5],
        [5, 6, 1, 5, 2],
        [7, 7, 7, 1, 4],
        [1, 6, 2, 2, 1]],

       [[1, 2, 3, 6, 4],
        [5, 3, 7, 2, 6],
        [5, 6, 6, 2, 4],
        [7, 2, 7, 4, 6]],

       [[3, 7, 1, 3, 6],
        [7, 7, 3, 7, 4],
        [4, 7, 5, 1, 5],
        [5, 4, 2, 3, 3]]])

参考文章:https://blog.csdn.net/chinacmt/article/details/78548420

2.random.seed()

seed()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。

seed()方法改变随机数生成器的种子,可以在调用其他随机模块函数之前调用此函数

语法:

random.seed(a=None, version=2)

a – 生成随机数的种子,可以设置为一个整数。没有返回值。

如果你不了解其原理,不必特别去设定seed,Python会帮你选择seed

(py3.6) E:\PYTHON>python
Python 3.6.13 |Anaconda, Inc.| (default, Mar 16 2021, 11:37:27) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>>
>>> random.seed()      # 随机数不一样
>>> a=random.random()
>>> a
0.13101058115666753
>>>
>>> random.seed()
>>> b=random.random()
>>> b
0.3843184581986723
>>>
>>>
>>>
>>> random.seed(1)     # 随机数一样
>>> c=random.random()
>>> c
0.13436424411240122
>>>
>>> random.seed(1)
>>> d=random.random()
>>> d
0.13436424411240122
>>>
>>> random.seed(2)
>>> e=random.random()
>>> e
0.9560342718892494

可以看到当seed()没有参数时,每次生成的随机数是不一样的,而当seed()有参数时,每次生成的随机数是一样的,同时选择不同的参数生成的随机数也不一样

参考文章:https://www.jianshu.com/p/551a95290645

                  https://blog.csdn.net/qq_42951560/article/details/112184965

猜你喜欢

转载自blog.csdn.net/aaaccc444/article/details/129993469