声明:这些完全是自己平时学习python一些简单的想法和思考,并不是系统学习python博客。
1.Python中的Type
首先,Python在实际中是可以使用type进行输出类型名字的,另外也可以通过isinstance()函数进行判断是否正确的
注意另外,在Python中我们是不支持++和--操作符的。但是我们可以使用+=,或者*=这种操作符
2.Booleans:
Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (&&, ||, etc.),That is to say,we use and ,or ,not insteard of || ,&&,! operator
总结起来就是我们使用and ,or ,not而不是&&,||或者!
3.String objects
对于string操作我们存在很多方法,但是这里我们仅仅列举几种比较常见的方法:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
s = 'heLLo'
s1 = 'hll'
print(s.capitalize()) # 这个函数是是输出标准化的字符串,也就是将首字母大写,其他的字母小写
print(s.upper()) # 将字符串全部变成大写
print(s.rjust(9)) # 将字符串填充为9个字符,不够的字符使用空格进行填充,右对齐
print(s.ljust(9)) # 将字符填充为9个字符,左对齐
print(s.center(20)) # 将字符进行中间对齐,总共的字符是9个
print(s1.replace('l', '(lll)')) # 使用lll代替l
print(s1.strip(' www')) # 使用www代替hll
4 Small Tips
可以利用**表示幂指数的作用,十分有用
>>> [x ** 2 for x in range(0,5)]
[0, 1, 4, 9, 16]
>>> [x ** 3 for x in range(0,5)]
[0, 1, 8, 27, 64]
>>> [x ** 4 for x in range(0,5)]
[0, 1, 16, 81, 256]
5 . Dictionary comprehensions
These are similar to list comprehensions, but allow you to easily construct dictionaries. 也就是说我们可以利用综合性字典,优化代码的数量。
>>> nums = [0,1,2,3,4]
>>> even_num_square = {x: x ** 2 for x in nums if x%2 == 0}
>>> print(even_num_square)
{0: 0, 2: 4, 4: 16}
6. 集合(Set)类型的相关说明
Python中的set和其他语言的类似,是一个无序不重复元素集合,(List是有序的)基本功能包括关系测试和消除重复的元素,集合的操作包含交集,差集等数学运算。
Python中我们是可以使用add,或者remove函数进行的,Python中set是使用{}
包含的。
但是我们也要注意一点,sets 支持x in set ,len(set) , for x in set。作为一个无序的集合,set 不记录元素的位置以及插入的位置,所以他是不支持indexing,切片等操作,以及其他类似序列的操作。所以通过这种set产生的数他是随机的,不是有序的。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'Difference between List and Set'
s1 = ['cat', 'dog', 'mouse'] # s1他是一个list所以他是有序的
for index, value in enumerate(s1):
print('index=%d, value= %s' % (index + 1, value))
s2 = {'cat', 'dog', 'mouse'} # s2他是一个集合Set,所以他是无序的,通过下标索引的方式进行访问是任意输出的
for index, value in enumerate(s2):
print('index=%d, value= %s' % (index + 1, value))
7.numpy使用注意
(1).numpy数组是一个值的网格,所有相同的类型,并由一个非负整数的元组索引。 维度的数量是数组的排名; 数组的形状是一个整数的元组,给出了每个维度的数组的大小。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np # 导入numpy这个包
a = np.array([1, 2, 3]) # 首先创建一个数组
print(type(a)) # 输出类型
print(a.shape) # 输出(3,)
print(a[0], a[1], a[2])
a[0] = 5
print(a) # 这个相当于是numpy是可以向矩阵化进行操作
b = np.array([[1, 2, 3], [4, 5, 6]]) # 这里需要注意一点,在输出二维数组及以上的时候,需要打二个括号
print(b.shape)
print(b)
(2). 另外还有一些函数创建一些常见的矩阵方法:
a1 = np.zeros(2) # 如果想要创建一个全0的矩阵,使用一个括号就可以了
a2 = np.zeros((2, 2)) # 创建全0的二维矩阵
a3 = np.ones((2, 2)) # 创建全1的元素
a4 = np.full((2, 2), 9) # 创建全9的元素,2*2的
a5 = np.eye(2) # 创建对角线元素为1的矩阵
a6 = np.random.random((2, 2)) # 创建一个随机数矩阵,2*2
(3). Python 中numpy的slice相关问题
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
b = a[:2, 1:3] # 这个numpy和普通list不同,他是可以对多维数组进行slice
print(b)
b[0, 0] = 99 # 这里特别需要注意,slice操作的是同一个数组,所以对slice之后的数据进行操作,那么原来的数据也会发生改变
print(a)
(4). 另外还要注意一点切片slice产生的shape是不一样的
import numpy as np # 导入numpy这个包
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
row_r1 = a[1, :]
row_r2 = a[1:2, :]
print(row_r1, row_r1.shape) # 仅仅使用这一种方法,取出来是一个向量(4,)
print(row_r2, row_r2.shape) # 按照这种方法取出来是和想的一样的
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape)
print(col_r2, col_r2.shape) # 按照这种方法输出结果是和普通一样的
Python中的Numpy可以同时输出多行进行操作
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a) # 这个是可以可以同时输出多个元素,第一个元素是行的索引,第二个是列的索引,二者相互映射
a[[0, 1, 2], [0, 1, 0]] += a[[0, 1, 2], [0, 1, 0]] + 12 # 通过这个行和列的索引相对应,可以同时操作很多数,简化了代码量
print(a)
8.Python中Boolean array indexing:
在python中我们可以通过boolean数组下表输出满足特定情况的元素,这个是十分实用的一种方法:
import numpy as np # 导入numpy这个包
a = np.array([[1, 2], [3, 4], [5, 6]])
bool_idx = a > 2 # 这个是输出比2大的元素,返回的结果是True和False
print(bool_idx)
print(a[a > 2]) # 这个是可以直接输出比2的元素,还是十分方便的
9. Python中的数据类型转换问题
import numpy as np # 导入numpy这个包
x = np.array([1, 2])
print(x.dtype) # 输出x的类型,默认整数是int32
x = np.array([1.0, 2.0])
print(x.dtype) # 默认浮点数的类型是float64
x = np.array([1, 2], dtype=np.float64) # 也可以进行显示的调用,进行强制类型转换
print(x)
10. Python中的常用数学运算:
(1)Python中的dot(),这个函数可以完成二个函数的内积操作
(2)Python中的sum()函数使用
import numpy as np # 导入numpy这个包
x = np.array([[1, 2], [3, 4]])
print(np.sum(x)) # 这个是最普通的输出结果
print(np.sum(x, axis=0)) # 这个是按照行输出,也就将列的所有元素输出来
print(np.sum(x, axis=1)) # 这个是按照列进行输出,将行的结果进行输出
(3)转置运算:
numpy中是可以通过transpose函数输出一个向量的转置的,但是对于一个秩一的向量来说,这个transpose是不起到任何作用的。
11. Python中的broadcasting机制:
在实际编程中,我们往往需要遇到将小的数组和大的数组进行某种运算,这时候我们往往可以利用Python中的广播机制进行处理。
import numpy as np # 导入numpy这个包
x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x) # 创建一个和x一样大小的数据,注意一开始是使用随机数进行初始化的
print(y)
for i in range(4):
y[i, :] = x[i, :] + v # 通过这种赋值操作,将x的每一行都加上v
print(y)
问题:当这里的x非常大的时候,我们需要进行v加到每一行进行循环的次数太多,也就是进行赋值需要一行一行扫描,这是十分浪费资源
vv = np.tile(v, (4, 2)) 代码说明:
这里我们是对v进行重复,这里的v代表的是需要重复的代码,4代表的是需要输出的行数,2表示对v复制二次
Broadcasting two arrays together follows these rules:
- If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.
- The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.
- The arrays can be broadcast together if they are compatible in all dimensions.
- After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
- In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension
这里注意一个小小的技巧,np.reshape(x,(3,2))可以进行一个矩阵重新定义其形状,还是比较方便的,比如说
x = np.array([1,2,3]) 一个行向量
y = np.reshape(x,(3,1)) 可以将一个行向量转换成列向量
' compute an outer product '
import numpy as np # 导入numpy这个包
v = np.array([1, 2, 3])
w = np.array([4, 5])
print(v)
print(np.reshape(v, (3, 1)) * w) # 计算二个向量的外积
x = np.array([[1, 2, 3], [4, 5, 6]]) # 这里的x的shape是(2,3)
print(x + v) # 这里的v是(3,),由于python的广播机制,将v变成了(2,3)这样就可以正常相加了
print(x + np.reshape(w, (2, 1))) # 将一个向量加到另一个向量的每一列,仍然是利用[ython
print(x ** 2) # 相当于对每一个元素进行操作
12. Python中scipy
Python中scipy是建立在numpy基础之上的,他继承了numpy搞笑的数值计算能力,将其扩展到具体的工程应用当中,具有十分重大的意义。
(1)图像的相关操作:imread,imsave,imresize等函数使用
'image processing'
from scipy.misc import imread, imsave, imresize # 首先从scipy导入基本的函数
img = imread('mouse.jpg') # 首先读取一幅图像,保存为array
print(img.dtype, img.shape) # 读取文件类型(uint32),以及大小,这个RGB图像,所以存在三个通道
img_tinted = img * [1, 0.95, 0.9] # 第一个通道是R*1红色分量没有发生变化,其他的二个通道的值发生了变化
img_tinted = imresize(img_tinted, (300, 300)) # 利用imresize函数重新调整图像大小
imsave('mouse1.jpg', img_tinted) # 将array数据重新保存为jpg图像文件
注意:The functions scipy.io.loadmat and scipy.io.savemat allow you to read and write MATLAB files
(2)计算距离:
scipy.spatial.distance.pdist computes the distance between all pairs of points in a given set
import numpy as np
from scipy.spatial.distance import pdist, squareform
x = np.array([[0, 1], [1, 0], [2, 0]])
print(x)
d = squareform(pdist(x, 'euclidean')) # 计算行与行之间的欧式距离
print(d)
13. Python中的Matplotlib
Matplotlib是一个绘图的库,在这里我们介绍一下malplotlib.pyplpt 简单的模块,这个和MATLAB中提供的很相像。
(1)Plotting:最重要的模块就是plot,这个允许你绘制2D简单的图像:
'sine and cosnie plot'
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1) # 计算x方向的点的值, 注意这里的函数是np.arange()而不是array()函数
y1 = np.sin(x) # 计算相应位置y的值
y2 = np.cos(x)
plt.plot(x, y1) # 绘制图形
plt.plot(x, y2) # 绘制图形
plt.xlabel('x axis label') # 绘制横坐标
plt.ylabel('y axis label') # 绘制纵坐标
plt.title('Sine and Cosine') # 绘制标题
plt.legend(['sin', 'cos']) # 绘制图例
plt.show() # 进行图形的显示
另外还有一点需要注意: plt.subplot(1, 2, 1) ,plt.subplot(1, 2, 2) 可以绘制子图
下面是显示图像的小程序:
'image show'
import numpy as np
from scipy.misc import imread
import matplotlib.pyplot as plt
img = imread('mouse.jpg')
img_tinted = img * [1, 0.95, 0.9] # 进行图形预处理
# Show the original image
plt.subplot(1, 2, 1)
plt.imshow(img) # 显示图像,但是这时候图像没有真正显示出来
# Show the tinted image
plt.subplot(1, 2, 2)
plt.imshow(np.uint8(img_tinted)) # 由于进行乘法运算得到的数据是float64,所以需要转换uint8
plt.show() # 最后才把图像真正的显示出来