Python

来自Shiyin's note
Shen讨论 | 贡献2017年9月30日 (六) 08:05的版本 →‎画图
跳到导航 跳到搜索

Python2 vs Python3

python的安装

Python程序的调试

jupyter

astropy

numpy

容器

  • container(数据结构)
  • 有3种: 序列,映射,集合

序列(sequence)

  • 序列有6总(列表,元组,字符串,Unicode字符串,buffer对象,xrange对象)
  • 序列的索引从0开始,对序列分片时包括开头,不包括结尾,比如A[3:4]只包括A列表的第四个成员
  • 序列的加号操作,[1,2,3]+[4,5,6] = [1,2,3,4,5,6]
  • 乘号参考加号 [1,2]*2 = [1,2,1,2]

通用序列操作

  • 索引,分片(slice),加,乘,迭代,最大,最小,长度
  • 索引从0开始,最后一个元素是-1(从右向左索引)
  • 分片: 访问倒数3个 A[-3:],访问正数3个A[:3]
  • 步长为2访问 A[0:10:2],步长可以为负,从右向左。
  • 相加 [1,2]+[3,4]-->[1,2,3,4]
  • 相乘 [1,2]*3 --> [1,2,1,2,1,2]
  • A=[None]*10 生成长度为10的空的列表
  • 成员资格:in,布尔运算符
  • len (长度),min,max
  • enumerate: 对一个列表或数组既要遍历索引又要遍历元素时
for index,text in enumerate(list): 
  print index ,text

列表

  • 列表的元素可以修改,字符串不能
  • x=[1,1,1],x[1]=2
  • del x[1]
  • x[1:1]=[2,3,4] 分片赋值,注意这相当于插入
  • 列表方法
  • append, count, extend, index, insert
  • pop (删除指定位置元素,并返回该元素,同时修改列表),实现栈的功能,入栈(push),出栈(pop),Python里面没有push,用append功能实现
  • remove,reverse,sort (sort的用法要注意,参考书的39页),sorted

元组

  • 不可变序列
  • (1,2,3) (1,)
  • 比如3*(40+2) 和3*(40+2,)的差别
  • tuple函数:把列表转换为元组
  • list: 把元祖装换为列表
  • 元组貌似没有什么用处,列表基本满足所有需要

字符串

  • 不可变
  • A='python‘
  • % 格式化

集合

  • 无序不重复集 set [1]

数组

  • numpy中有个数组ndarray的数据结构 [2]
array() 可以将列表等转化为数组
asarray()和array差不多,但是不一定需要复制

函数

  • 在参数名之前使用一个星号,就是让函数接受任意多的位置参数。[3]

lambda 函数

>>> g = lambda x:x+1 

看一下执行的结果:    >>>g(1)   >>>2 可以这样认为,lambda作为一个表达式,定义了一个匿名函数,上例的代码x为入口参数,x+1为函数体:f(x)=x+1 参见http://www.cnblogs.com/evening/archive/2012/03/29/2423554.html

模块

  • glob 查找文件位置
  • os 系统的一些变量
dir=os.getenv('bc03_dir')

内部变量,魔方方法

  • __file__
查找源文件位置 print(ppxf.__file__)
  • __name__,__main__
if __name__ == '__main__': test()
  • __init__ (初始化方法 )
def __init__(self)
  • __all__ (显示可见功能)
copy.__all__
  • __doc__ (文档)
print(copy.copy.__doc__)

脚本和模块

画图

  • matplot库[4]
  • pylab combines pyplot with numpy into a single namespace. This is convenient for interactive work, but for programming it is recommended that the namespaces be kept separate, e.g.:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.clf()  #clear the current figure
plt.subplot(211)
plt.plot(x, y)
plt.show()
  • options for the color characters are:
'r' = red
'g' = green
'b' = blue
'c' = cyan
'm' = magenta
'y' = yellow
'k' = black
'w' = white
  • Options for line styles are
'-' = solid
'--' = dashed
':' = dotted
'-.' = dot-dashed
'.' = points
'o' = filled circles
'^' = filled triangles
  • pmesh,pcolormesh: 画二维的平面分布的图
  • colorbar

链接

  • 带下划线变量的意义 [5]