一、numpy模块初识

NumPy(Numerical Python)是Python的一种开源的数值计算扩展。这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix)),支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。

二、生成0~1的数组:np.random.random

import numpy as np  # 导入模块
array = np.random.random(6)  # 随机生成0~1的随机数,参数表示个数
print(array)  # 打印数组
# 输出结果
# [0.291581   0.94386352 0.17057392 0.68169912 0.71410809 0.48869206]

三、正态分布(一维):np.random.randn (n)

# 正态分布
import numpy as np  # 导入模块

array = np.random.randn(6)  # 随机生成0~1的随机数,参数表示个数
print(array)  # 打印数组
# 输出结果
# [ 0.36854586 -0.14679773  0.8571154   0.32133017 -0.19686295 -1.13227268]

四、正态分布(二维):np.random.randn (2,n)注意结果中括号数量

# 正态分布
import numpy as np  # 导入模块

array = np.random.randn(2,6)  # 随机生成0~1的随机数,参数表示个数
print(array)  # 打印数组
# 输出结果
# [[ 0.07126508 -1.00878137 -2.55524076 -0.30622609 -0.15677762  0.29451671]
#  [ 0.82189096  0.15222826 -0.22179691 -1.0938879  -0.53919851  1.01396701]]

五、正态分布(多维):np.random.randn (x,y)

# 正态分布
import numpy as np  # 导入模块

array = np.random.randn(5,6)  # 随机生成0~1的随机数,参数表示个数
print(array)  # 打印数组
# 输出结果
# [[-1.54956132  0.17128378 -0.50218919 -0.76759462 -1.25870508  0.81819736]
#  [-1.5647944  -0.53984111 -0.67357775  1.32124529 -0.78602524 -0.24988648]
#  [ 0.03747857  0.4691213   0.64394841 -0.0338305   0.32232235  0.37518126]
#  [ 0.99779461  0.57622062 -0.80662965  0.01579862 -0.03792585  0.3087749 ]
#  [ 0.92132549  0.85622781  1.46119892  0.05633672  1.44731465  0.64289519]]

六、遍历数组(嵌套循环)

# 正态分布
import numpy as np  # 导入模块

array = np.random.randn(3, 3)  # 随机生成0~1的随机数,参数表示个数
print(array)  # 打印数组
print("-----------------------")
for array1 in array:  # 一重遍历
    for array2 in array1:  # 二重遍历
        if (array2 > 0) and (array2 < 1):  # 添加所需条件
            print(array2)  # 打印

# 输出结果
# [[-0.06447758  0.50622103 -1.06414826]
#  [-0.93554389 -0.79832955 -1.92540642]
#  [ 1.10755039  0.76215104  0.8568204 ]]
# -----------------------
# 0.506221028078229
# 0.7621510394939643
# 0.8568204017768024

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐