Python ——序列生成函数:linspace()、arange()、range()、reshape()

作为序列生成器,numpy.linspace()函数用于在线性空间中以均匀步长生成数字序列,返回array;numpy.arange()函数用于生成固定步长的数字序列,返回array;range() 函数与arange()类似,但返回int类型list,不在numpy模块下,与list()同时使用;reshape()函数将一维数组转化为多维数组,不可用于list。
1、numpy.linspace()函数
结构:numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
其中:
start:数字的起始值
stop:数字的末尾值
num:生成的数字数量,默认为50
endpoint:若为True(默认取值),结果包含末尾值;若为False,结果不包含末尾值,步长也会发生变化
retstep:若为True,结果包含样本步长;若为False(默认取值),结果不包含样本步长
dtype:确定数据类型,若未限制,那么从其他输入参数推断其类型。
举例:

> x=np.linspace(1,2,5)
array([1.  , 1.25, 1.5 , 1.75, 2.  ])
> x=np.linspace(1,2,5,endpoint=False)
array([1. , 1.2, 1.4, 1.6, 1.8])
> x=np.linspace(1,2,5,retstep=True)
(array([1.  , 1.25, 1.5 , 1.75, 2.  ]), 0.25)
> x=np.linspace(1,2,5,retstep=False)
array([1.  , 1.25, 1.5 , 1.75, 2.  ])
> x=np.linspace(1,4,5,dtype='int')
array([1, 1, 2, 3, 4])
import numpy as np
from matplotlib import pyplot as plt
x=np.linspace(1,2,8)
y=2*x+1
plt.figure()
plt.plot(x,y,'o')

2、numpy.arange()函数
arange(start, end, step),以start开始,以stop终止,不包含末尾值,步长为step,默认步长为1。 可以使用float型数据。
当未指定start及stop时,以固定步长1生成以0开头的若干个数字。

> x=np.arange(1,10,2)
array([1, 3, 5, 7, 9])
> x=np.arange(1,10)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
> x=np.arange(5)
array([0, 1, 2, 3, 4])
> x=np.arange(1.2,3)
array([1.2, 2.2])
> x=np.arange(1.2,3,0.5)
array([1.2, 1.7, 2.2, 2.7])

3、range()函数
range(start, end, step),返回一个list对象,起始值为start,终止值为end,但不含终止值,步长为step。 只能创建int型list

> x=list(range(1,10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
> x=list(range(1,10,2))
[1, 3, 5, 7, 9]
> x=list(range(1.0,10,2))
      2 x

TypeError: 'float' object cannot be interpreted as an integer

4、reshape()函数
reshape()函数将一维数组转化为多维数组


> x=np.arange(8).reshape(2,4)
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])

> x=np.arange(6).reshape(3,2)
array([[0, 1],
       [2, 3],
       [4, 5]])
> x=np.linspace(1,2,8).reshape(2,4)
array([[1.        , 1.14285714, 1.28571429, 1.42857143],
       [1.57142857, 1.71428571, 1.85714286, 2.        ]])

Original: https://blog.csdn.net/weixin_42540470/article/details/117814777
Author: AlligatorPear
Title: Python ——序列生成函数:linspace()、arange()、range()、reshape()

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/759085/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球