Python数组、列表、矩阵之间的相互转换
import numpy as np
my_list = [[1, 2, 3], [4, 5, 6]] # 列表定义
my_array = np.array([[1, 2, 3], [4, 5, 6]]) # 数组定义(这里是二维数组)
my_matrix = np.mat([[1, 2, 3], [4, 5, 6]]) # 矩阵定义
print('-----------------------列表转数组、矩阵----------------------')
list_to_array = np.array(my_list) # 列表转数组
list_to_matrix = np.mat(my_list) # 列表转矩阵
print('-----------------------数组转列表、矩阵----------------------')
array_to_list = my_array.tolist() # 数组转列表
array_to_matrix = np.mat(my_array) # 数组转矩阵
print('-----------------------矩阵转列表、数组----------------------')
matrix_to_list = my_matrix.tolist() # 矩阵转列表
matrix_to_array = np.array(my_matrix) # 矩阵转数组
python自带编辑器的缩进和取消缩进快捷键:
整体左移
Ctrl+【
整体右移
Ctrl+】或者tab
axes - subplot - axis之间的关系
可以把fig想象成画板,axes/subplot是上面的画纸,他们的区别在:axes是自由摆放的图标,甚至可以相互重叠,而subplot是“自动对齐到网格”。也就是说subplot内部其实也是调用的axes,只不过规范了各个axes的排列罢了。axis坐标轴。
fig=plt.figure()
ax=fig.add_subplot(111)
ax.set(xlim=[0,4],ylim=[0,8],title='An example axes',ylabel='Y-Axis',xlabel='X-Axis')
plt.show()
fig=plt.figure()
ax=fig.add_axes([0.1,0.1,0.8,0.8]) #四个参数分别为起始位置以及图像的宽高,使用add_axes()方法可以控制图像的位置
ax.set(xlim=[0,4],ylim=[0,8],title='An example axes',ylabel='Y-Axis',xlabel='X-Axis')
plt.show()
若保存图像的时候想要去除画板,只保留画纸,可使用
plt.savefig(figName,bbox_inches='tight',dpi=600,pad_inches=0.0)
list.append()与list.extend()的区别
list.append(object) 向列表中添加一个对象object
list.extend(sequence) 把一个序列seq的内容添加到列表中
music_media = ['compact disc', '8-track tape', 'long playing record']
new_media = ['DVD Audio disc', 'Super Audio CD']
music_media.append(new_media)
print music_media
>>>['compact disc', '8-track tape', 'long playing record', ['DVD Audio disc', 'Super Audio CD']]
使用append的时候,是将new_media看作一个对象,整体打包添加到music_media对象中。
music_media = ['compact disc', '8-track tape', 'long playing record']
new_media = ['DVD Audio disc', 'Super Audio CD']
music_media.extend(new_media)
print music_media
>>>['compact disc', '8-track tape', 'long playing record', 'DVD Audio disc', 'Super Audio CD']
使用extend的时候,是将new_media看作一个序列,将这个序列和music_media序列合并,并放在其后面。
使用 @property
Python内置的@property装饰器就是负责把一个方法变成属性调用的:
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
@property的实现比较复杂,我们先考察如何使用。把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作:
>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
...
ValueError: score must between 0 ~ 100!
还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:
class Student(object):
@property
def birth(self):
return self._birth
@birth.setter
def birth(self, value):
self._birth = value
@property
def age(self):
return 2015 - self._birth
上面的birth是可读写属性,而age就是一个只读属性,因为age可以根据birth和当前时间计算出来。