perfectism's blog

物来顺应,未来不迎,当时不杂,既往不恋

0%

Python学习笔记

Python学习笔记

基本语法

打印输出

1
2
3
4
5
6
7
print("hello world")
print("-"*10)
print("hello","world")
#打印变量值
print("width : %s, height : %s channels : %s" % (width, height, channels))
#打印矩阵
print(image)

代码注释

代码缩进:python对代码缩进的要求非常严格

多行语句的分割

使用\将代码分割成多行

1
2
print("Hello,World.Hello,World.\
Hello,World.Hello,World.")

变量

赋值方式

1
2
string1 = string2 = string3 = "Hello,World"
string1, string2, string3 = "Hello", "World","Hello,World"

数据类型及其索引

数字

1
2
3
4
5
6
7
8
9
10
11
float_num = 10.000

print(float_num)
print("%f" % float_num)
print("%.2f" % float_num)
print("%.4f" % float_num)
#ouput
10.0
10.000000
10.00
10.0000

字符串

1
2
3
4
5
6
7
8
9
10
11
12
string = 'Hello,World' #双引号也可以
string1 = string[0:11]
string2 = string[0:5]
string6 = string[:5] #注意第五个字符不显示
string3 = string[-1]
string4 = string[-5:-1]
#ouput
Hello,World
Hello
Hello
d
worl

列表

列表是一种容器型数据类型,可以实现多种数据类型的嵌套,元素可重新赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
list1 = [ "Hello,World", 100 , 10.00 ]
list2 = [123, 'Hi']

print(list1) # 输出整个list1 列表元素
print(list1[0]) # 输出列表的第1 个元素
print(list1[1:]) # 输出从第1 个索引开始至列表末尾的所有元素
print(list1[-1]) # 输出列表的最后一个元素
print(list1 + list2) # 输出列表的组合
list1[0] = "0"
print(list1)
#output
['Hello,World', 100, 10.0]
Hello,World
[100, 10.0]
10.0
['Hello,World', 100, 10.0, 123, 'Hi']
['0', 100, 10.0]

元组

另一种容器型数据类型,基本性质、索引值操作与列表相同,但其元素不能重新赋值

1
2
3
tuple1 = ( "Hello,World", 100 , 10.00 )
tuple2 = (123, 'Hi')
print(list1) # 输出整个tuple1 列表元素

字典

列表与元组为有序的元素组合,字典通过键值来操控元素

1
2
3
4
5
6
7
8
9
10
11
12
13
dict_info = {"name": "Tang", "num":7272, "city": "GL"}
dict_info["city"] = "changsha"

print (dict_info) # 输出整个dict_info 字典
print(dict_info["city"])
print (dict_info.keys()) # 输出dict_info 的所有键值
print (dict_info.values()) # 输出dict_info 的所有值

#output
{'name': 'Tang', 'num': 7272, 'city': 'changsha'}
changsha
dict_keys(['name', 'num', 'city'])
dict_values(['Tang', 7272, 'changsha'])

tuple

构造一个元组

面向对象的方法-类

类是用来描述具有相同属性和方法的对象的集合,定义了该集合中每个对象的共有属性和方法,对象是类的实例

类的创建、继承与重写

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
class People:

def __init__(self, name, age):
self.name = name
self.age = age

def dis_name(self):
print("name is:",self.name)

def set_age(self, age):
self.age = age

def dis_age(self):
print("age is:",self.age)

class Student(People): #继承父类
def __init__(self, name, age, school_name):
self.name = name
self.age = age
self.school_name = school_name

def dis_student(self):
print("school name is:",self.school_name)

def dis_name(self): #子类中对父类进行重写
print("名字:",self.name)

student = Student("Wu", "20", "GLDZ") #创建一个Student 对象
student.dis_student() #调用子类的方法
student.dis_name() #调用子类的方法,已重写
student.dis_age() #调用父类的方法
student.set_age(22) #调用父类的方法
student.dis_age() #调用父类的方法

next()返回迭代器的下一个值

iter()生成迭代器

Matplotlib

画函数图像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import matplotlib.pyplot as plt
import numpy as nps
%matplotlib inline
x = np.arange(-10,10,0.01)
# y = (np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x))
y = np.where(x<0,0,x)
# y = np.sin(x)
plt.plot(x, y)
plt.title("ReLU",fontsize = 10)
# plt.xlabel("horizontal axis", fontsize = 10)
# plt.ylabel("vertical axis",fontsize = 10)
plt.tick_params(axis="both", labelsize = 10)
ax = plt.gca() # get current axis 获得坐标轴对象
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none') # 将右边 上边的两条边颜色设置为空 其实就相当于抹掉这两条边
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left') # 指定下边的边作为 x 轴 指定左边的边为 y 轴
ax.spines['bottom'].set_position(('data', 0)) #指定 data 设置的bottom(也就是指定的x轴)绑定到y轴的0这个点上
ax.spines['left'].set_position(('data', 0))
plt.show()

显示图像报错

pyplot显示图像报错:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers)

原因:用cv2.imread读进来的图片是uint8格式的,每个点的像素值在[0,255]之间,之前定义的图片占位符是float32,所以会直接将0-255之间的整数变成小数,但是并没有归一化! 要显示float32格式的图片,还需要一步操作:

image = image/255.
原文链接:https://blog.csdn.net/aaon22357/article/details/82736792

解决:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import cv2.cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
def get_image_info(image):
print(type(image)) # <class 'numpy.ndarray'>
print(image.shape[1:3]) # 显示高,宽,通道数
# print(image.size) # 总的像素数据大小=高*宽*通道数
# print(image.dtype) # 显示像素数据类型
# pixel_data = np.array(image) # 通过numpy获取像素值
# # print(pixel_data)
# print(image)
print("hi,python")
src = cv.imread("D:/IMG_20161227_154705.jpg")
plt.imshow(src)
plt.show()
edit = cv.resize(src, (224, 224)).astype("float32")
edit = cv.cvtColor(edit, cv.COLOR_BGR2RGB)
edit = edit/255.
#plt.imshow(edit.astype('uint8')),用此句不用上一句
plt.imshow(edit)
get_image_info(edit)

pickle块

模块 pickle 实现了对一个 Python 对象结构的二进制序列化和反序列化。

json也是一种序列化格式。

collections

deque双向队列

1
2
3
4
5
6
7
8
9
10
11
12
>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
... print(elem.upper())
G
H
I

>>> d.append('j') # add a new entry to the right side
>>> d.appendleft('f') # add a new entry to the left side
>>> d # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

yield

带yield的函数是一个生成器,而不是一个函数了,这个生成器有一个函数就是next函数,next就相当于“下一步”生成哪个数,这一次的next开始的地方是接着上一次的next停止的地方执行的,所以调用next的时候,生成器并不会从foo函数的开始执行,只是接着上一步停止的地方开始,然后遇到yield后,return出要生成的数,此步就结束

在深度学习中批量生成数据时经常yield(x,y)

其中x为数据,y代表数据标签

找到字符串中的数字

1
2
3
4
import re
s='zs10nj23kl'
f1=re.findall('(\d+)',s)
print(f1)