第一章 python的入门

本章节主要介绍了python的一些基本知识,包括python的安装和两个库的使用,一个是NumPy库和Matplotlib库。后文的深度学习的学习代码也主要是基于这两个库完成的。本文主要介绍这两个库的基本使用方法介绍。1

1.1 python的数据类型和算数计算

1.1.1.算数计算

#1.算数运算
a=2;b=3;
a1=a+b    #加法运算
a2=a-b    #减法预算
a3=a*b    #乘法运算
a4=a/b    #除法运算,结果不特别说明都是浮点数,小数点后16位
a5=a**b   #次方运算
print(a1,a2,a3,a4,a5)

结果:

5  -1  6    0.6666666666666666   8

1.1.2.数据结构

type(X)是求取X数据结构的一个函数。

#2.数据结构(整数,小数,字符串,布尔型)
type(10)        #整数
type(10.23)     #小数
type('hello')   #字符串
hungry=True
type(hungry)   #布尔型

结果:

type(10)
Out[2]: int

type(10.23)
Out[3]: float

type('hello')
Out[4]: str

hungry=True
type(hungry)
Out[5]: bool

1.1.3.变量

变量:动态语言类型的编程语言,不需要提前定义,赋的值是什么类型,变量就自动变成了什么类型

#3.变量    
a=1;b=2;
c=a+b;
print(c)
type(c)

结果:

int

1.1.4.列表

列表中数字的序号是从零开始的。len(a)函数是求取列表的长度。

a=[1,2,3,4,5]
print(a)
print(len(a))

结果:

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

列表的切片操作a[:] :冒号前面代表从第几个数开始,省略代表0;冒号后面代表从第几个数结束,省略代表最后一个数

a[1:3]
Out[8]: [2, 3]
a[:3]
Out[9]: [1, 2, 3]
a[1:]
Out[10]: [2, 3, 4, 5]

1.1.5.字典

字典:以键值对存储信息{字符串:数据}

xukaihui={'hight':180,'weight':75}  #创建字典
print(xukaihui)                     #输出字典信息
xukaihui['hight']                   #检索字符串对应信息,单向检索
xukaihui['age']=25                  #添加新的信息

输出:

xukaihui={'hight':180,'weight':75}  #创建字典

print(xukaihui)                     #输出字典信息
Out[1]:{'hight': 180, 'weight': 75}

xukaihui['hight']                   #检索字符串对应信息,单向检索
Out[2]: 180

xukaihui['age']=25                  #添加新的信息

xukaihui['age']                     #检索新添加的信息
Out[3]: 25

1.1.6.布尔型(逻辑运算)

逻辑运算,输出的结果为布尔型

a=1;b=2
print(a<b)

输出:

Out[1]:True
1
tired=True        #累了?
thirsty=False     #渴了?
not tired                #否逻辑运算
tired and thirsty         #与逻辑
tired or  thirsty        #或逻辑
not tired or  thirsty    #组合逻辑

输出:

not tired                #否逻辑运算
Out[1]: False

tired and thirsty        #与逻辑
Out[2]: False

tired or  thirsty        #或逻辑
Out[3]: True

not tired or  thirsty    #组合逻辑
Out[4]: False

1.1.7.if语句

a=1;
if a==2:
    print('正确')    #按空格,自动缩进四个空白字符
else:
    print('错误') 

输出:

Out[1]:错误

1.1.8. for 语句

for i in [1,2,3]:
    print(i)
print()

输出:

Out[1]:
1
2
3

1.1.9. 子函数的定义与调用

函数的定义:

def hello():
    print('hello world!')

def hi(name):
    print('hello'+' '+name+'!');
    
name='徐凯晖'
hi(name)     #函数可以取参数

函数的调用:

hello()    #函数调用

name='徐凯晖'
hi(name)     #函数可以取参数

输出:

Out[1]:hello world!
Out[2]:hello 徐凯晖!

1.1.10. 定义类

class Man:
    """示例类"""   # 示例类

    def __init__(self, name):
        self.name = name           #生成实例变量,在类里面能够通用
        print("Initilized!")

    def hello(self):
        print("Hello " + self.name + "!")

    def goodbye(self):
        print("Good-bye " + self.name + "!")

m = Man("David")
m.hello()
m.goodbye()

输出:

Out[1]:Initilized!
Out[2]:Hello David!
Out[3]:Good-bye David!

NumPy(Numerical Python)是Python的一种开源的数值计算扩展。这种工具可用来存储和处理大型矩阵,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库 1

1.2 Numpy库

1.2.1 导入numpy库

import numpy as np      #导入numpy库,并且把名字叫做np

1.2.2 生成numpy数组

>>>x=np.array([1,2,3,4])   #numpy库中数组的生成需要调用numpy.array()     
>>>print(x)
[1 2 3 4]
>>>type(x)           #判定该数组类型
numpy.ndarray        #该数组的类为numpy.ndarray       

1.2.2 numpy数组的算数运算

>>>x=np.array([2,3,4,5]);
>>>y=np.array([1,2,3,4]);     # 数组运算一定要保持元素个数的一致
>>>print(x+y)             #加法运算
[3 5 7 9]
>>>print(x-y)             #减法运算
[1 1 1 1]
>>>print(x*y)             #乘法运算
[ 2  6 12 20]
>>>print(x/y)             #除法运算
[2.         1.5        1.33333333    1.25]

1.2.2 numpy的n维数组与运算

>>>A=np.array([[1,2],[3,4]])
>>>print(A)
[[1 2] [3 4]]
>>>A.shape      #查看矩阵的类型
(2, 2)          #是一个2x2的矩阵
>>>A.dtype      #查看矩阵的数据结构
dtype('int32')  #是一个32位的数据类型
1234567
>>>B=np.array([[3,4],[5,6]])
>>>print(A+B)      #n维数组的加法   对应元素相加
[[ 4  6] [ 8 10]]  #对应元素相加
>>>print(A*B)      #n维数组的乘法    对应元素相乘
[[ 3  8] [15 24]]  #对应元素相乘

1.2.2 数组的广播

不同维度的数组也是可以进行运算的,通过广播这个功能,它可以把小的数组给扩展成与大的数组相匹配的数组2

>>>a1=np.array([[1,2],[3,4]])
>>>a2=10
>>>a3=np.array([10,20])
>>>print(a1*a2)      #a2扩展为:[[10,10],[10,10]]
[[10 20] [30 40]]
>>>print(a1*a3)      #a3扩展为:[[10,20],[10,20]]
[[10 40] [30 80]]

imgimg

1.2.3 访问numpy数组元素的三种方法

第一种是按元素位置进行访问,元素的索引从0开始

>>>print(a1[0])     #访问第一行元素
[1 2]
>>>print(a1[0,0])   #访问第一行第一个数字
1

第二种是循环进行访问(逐行进行访问)

>>>for i in a1:
    print(i)
[1 2]
[3 4]

第三种是把数组变为一行,然后按行进行元素访问

>>>A1=a1.flatten()  #把一个多元数组变为一个一元数组
>>>print(A1)
[1 2 3 4]
>>>A1[A1>2]   #把一元数组A1中大于2的数给列出来了
>>>print(A1[A1>2])
[3 4]

matplotlib库:该库是python的一个绘图库,进行数据的可视化处理。

1.3 matplotlib库

1.3.1 库的导入

>>>import numpy as np      #导入numpy库,并且把名字叫做np
>>>import matplotlib.pyplot as plt    #导入matplotlib库

1.3.2 生成数据

>>>x=np.arange(0,6,0.1)  #以0.1为一个间隔,生成0-6的数据
>>>y1=np.sin(x) 
>>>y2=np.cos(x) 

1.3.3 绘制图形(简单)

>>>plt.plot(x,y1)        #图形的绘制
>>>plt.show()            #图形的显示

结果:
img

1.3.4 绘制图形(完整)

>>>plt.plot(x,y1,linestyle="--",label="sin")       #图像的线型,颜色,大小,标签的设置
>>>plt.plot(x,y2,linestyle="--",label="cos")

>>>plt.xlabel("x")   #x轴标签                     #坐标轴的信息设定
>>>plt.xlabel("y")   #y轴标签
>>>plt.title('sin & cos')    #标题
>>>plt.legend()     #加上图例,也就是曲线的标签显示
>>>plt.show() 

结果:
img

1.3.5 图片的读取显示

>>>import matplotlib.pyplot as plt        # 调用matplotlib.pyplot库 
>>>from matplotlib.image import imread   #调用matplotlib.image库中的impread函数,后面调用就不用加前缀了  

>>>img1=imread("E:\\pic.png")     #读取照片
>>>plt.imshow(img1)                #照片进行显示
>>>plt.show()

扩展:通过使用opencv库也能够进行图片的读取显示,不过是以窗口的形式

>>>import cv2   
>>>import matplotlib.pyplot as plt        # 调用matplotlib.pyplot库 
>>>from matplotlib.image import imread   #调用matplotlib.image库中的impread函数,后面调用就不用加前缀了 
>>>img = cv2.imread("E:\\wangye.jpg")  #读取图片
>>>cv2.namedWindow("Image")            #创建显示窗口
>>>cv2.imshow("Image", img)            #在窗口中显示图片
>>>cv2.waitKey (0)                     #使窗口的图片显示时间拉长
>>>cv2.destroyAllWindows()             #删除窗口的,不影响
thon
>>>import cv2   
>>>import matplotlib.pyplot as plt        # 调用matplotlib.pyplot库 
>>>from matplotlib.image import imread   #调用matplotlib.image库中的impread函数,后面调用就不用加前缀了 
>>>img = cv2.imread("E:\\wangye.jpg")  #读取图片
>>>cv2.namedWindow("Image")            #创建显示窗口
>>>cv2.imshow("Image", img)            #在窗口中显示图片
>>>cv2.waitKey (0)                     #使窗口的图片显示时间拉长
>>>cv2.destroyAllWindows()             #删除窗口的,不影响
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追寻远方的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值