中文Python笔记

  • 笔记来自 http://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/index.ipynb 学习摘抄。

中文Python笔记

01.python工具¶

简介

荷兰人 guido van rossum编写。 python3与python2不兼容,但部分新特性移植到2.6/2.7中。 import this显示python之禅。

In [1]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

解释器 ipython中

magic命令:%开头 类似命令行 。列出所有magic命令是%lsmagic。分两种

  • line magic 一个百分号大头 作用一行 automagic on %非必须
  • cell magic:两个百分号带头 作用本cell

!用来执行外部命令。 sum?用来查看帮助。

notebook

jupyter notebook conda list 列出第三方工具包,cell中执行的话!conda list 更新 conda update conda conda update Anconda 操作 conda install/update/remove package spyder编辑器

In [5]:
%lsmagic 
Out[5]:
Available line magics:
%alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %cls  %colors  %config  %connect_info  %copy  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %matplotlib  %mkdir  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.
In [19]:
%%file a.py
print('hello')
Overwriting a.py
In [25]:
# %load a.py
print('hello')
%whos
%colors linux
hello
Variable   Type      Data/Info
------------------------------
this       module    \Anaconda2\lib\this.pyc'>

基础

数据类型

简单数学 字串 列表 集合 字典

In [1]:
%pylab
print 1+2,1-5,8*2,5/2,5.0/2,7//2,7%2#加减乘除 除 整除 取余数

s= 'a a'+"b b"+"""c c"""
print s[2:5],s.split(' '),len(s)

l=[1,2,3]+[4,5,6]
print l,l[2:-1],len(l),l.append(5),l.append(['a','b']),l.extend([4,5,6])
print l

s={1,2,3,4,5,5,6}
s2={4,5,6,7,8,9}
print len(s),s.add(9),s,s2,s&s2,s|s2,s-s2,s^s2#交并差对称差

d={'A':90,'B':70}
d['B']=75#update
d['C']=60#new
print len(d),d['A'],d['B'],d.keys(),d.values(),d.items()

from numpy import array
a=array([1,2,3])
from matplotlib.pyplot import plot
plot(a,a**2)
Using matplotlib backend: Qt5Agg
Populating the interactive namespace from numpy and matplotlib
3 -4 16 2 2.5 3 1
ab  ['a', 'ab', 'bc', 'c'] 9
[1, 2, 3, 4, 5, 6] [3, 4, 5] 6 None None None
[1, 2, 3, 4, 5, 6, 5, ['a', 'b'], 4, 5, 6]
6 None set([1, 2, 3, 4, 5, 6, 9]) set([4, 5, 6, 7, 8, 9]) set([9, 4, 5, 6]) set([1, 2, 3, 4, 5, 6, 7, 8, 9]) set([1, 2, 3]) set([1, 2, 3, 7, 8])
3 90 75 ['A', 'C', 'B'] [90, 60, 75] [('A', 90), ('C', 60), ('B', 75)]
Out[1]:
[]

整形 浮点型 字符串 列表 字典 numpy数组 长整型 布尔型 元组 集合 pandas 自定义

数字

整形、长整型

  • 整形 加减乘除/ 乘方** 取余数%
  • 整形只能返回整形,除法也不例外
  • 超出范围,自动长整型;如果强制,需要加L
In [29]:
import sys 
print sys.maxint,1+2,1-5,8*2,5/2,5.0/2,7//2,7%2,\
6**2,type(56l),type(sys.maxint+1)#加减乘除 除 整除(返回比结果小的最大整数) 取余数
2147483647 3 -4 16 2 2.5 3 1 36  

浮点数

  • 任何数和浮点数运算结果为浮点数
In [24]:
print 3.4-3.2#print 自动处理了
3.4-3.2
import sys
print sys.float_info
0.2
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

复数 优先级 函数 强制类型转换 进制 原地计算 链式比较

  • j表示虚部
  • 优先级 ()> * > / // % > + -
  • abs round max min
  • int()
  • 进制表示 0xff 067 0b0011001 1e-6
  • 原地计算 +=
  • 比较 < > <= >= == != 链式比较 1<=x<3
In [9]:
a=1+2j
print type(a),a.real,a.imag,abs(-45.5),round(4.5),round(-4.3),int(round(2.9)),0xff,067,0b1100,1e-6,1<2<3
 1.0 2.0 45.5 5.0 -4.0 3 255 55 12 1e-06 True
Variable   Type        Data/Info
--------------------------------
a          complex     (1+2j)
f          function    

字符串

  • 单引号 双引号 三引号 乘法 加法
  • len split join replace upper lower strip lstrip str repr hex oct bin int float ...... dir(s)
  • 格式化字符串 .format 和 %

索引和切片

  • 索引和分片[lower:upper:step]包括lower不包括upper省略意味着头尾为负数表示反向找,step为负数表示逆序
In [60]:
s='abc'+"def"+"""ghi"""+'jkl'*3
print s,len(s),s.split('j'),\
'*'.join(['^','$','T']),'*'.join(s),\
s.replace('j','J'),\
s.upper(),dir(s),str(1+1),repr(1+1),\
hex(255),oct(255),bin(255),int('ff',16),\
'{1}--{0}--{2}'.format('a','b','c'),'hello:{name},you are {:10.2f} old'.format(24,name='lilei'),\
'hello:%s'%('hanmeimei'),\
s[::-1],s[::2]
abcdefghijkljkljkl 18 ['abcdefghi', 'kl', 'kl', 'kl'] ^*$*T a*b*c*d*e*f*g*h*i*j*k*l*j*k*l*j*k*l abcdefghiJklJklJkl ABCDEFGHIJKLJKLJKL ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 2 2 0xff 0377 0b11111111 255 b--a--c hello:lilei,you are      24.00 old hello:hanmeimei lkjlkjlkjihgfedcba acegikjlk
In [39]:
import string
s='hello!lilei.I"m hammeimei.'
intab=string.punctuation
outtab=' '*len(string.punctuation)
trans=string.maketrans(intab,outtab)
s.translate(trans)
Out[39]:
'hello lilei I m hammeimei '

列表

  • [] list 不同类型也可以
  • len + 乘法
  • 索引切片同上,不同的是切片索引可以修改内容,因为list是mutable,字串是immutable,所以字串方法返回新的字串,原字串保持不变,如需要改变字符串,需要重新赋值。 ### 可变和不可变类型
  • 可变 list dictionary set numpyarray userdefineobject
  • 不可变 string integer float long complex string tuple frozenset
In [89]:
l=[1,2,3,'a','b']+list('def')[0:3]+[7,8]*2
print l,l[::-1]
l[3:5]=[4,5]
l[-2:]=[9,10]
print l
print l,l[2:-1],len(l),l.append(5),l.append(['a','b']),l.extend([4,5,6])
[1, 2, 3, 'a', 'b', 'd', 'e', 'f', 7, 8, 7, 8] [8, 7, 8, 7, 'f', 'e', 'd', 'b', 'a', 3, 2, 1]
[1, 2, 3, 4, 5, 'd', 'e', 'f', 7, 8, 9, 10]
[1, 2, 3, 4, 5, 'd', 'e', 'f', 7, 8, 9, 10] [3, 4, 5, 'd', 'e', 'f', 7, 8, 9] 12 None None None

元组

  • 与列表类似,也是有序序列,但tuple不可变,用()、tuple()生成
  • 支持索引切片,
  • 方法 计数count 位置index
In [27]:
t=(1,2,3)
t2=tuple([2,3,4])
print t,t2[::-1],t.count(5),t.index(2)
(1, 2, 3) (4, 3, 2) 0 1

速度对比

  • tuple比list快,这里为啥不快,不知道
In [37]:
%timeit l=list(range(10000))
%timeit s=tuple(range(10000))
%timeit for i in l:pass
%timeit for i in s:pass
The slowest run took 4.90 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 225 µs per loop
1000 loops, best of 3: 216 µs per loop
10000 loops, best of 3: 25.6 µs per loop
10000 loops, best of 3: 25.5 µs per loop

字典

  • 再一些语言中称为 hash map 是键值对组成的数据结构
  • {}或者dict()方法 dict([('a',1),('b',2)])
  • 插入 a['key']=value 查看a['key'] 更新同插入,也可以利用索引直接更新键值对 删除del a['key'] 更新update(dict)
  • 字典无顺序
  • 键必须是不可变类型,值可以是任意python对象,建议整形、字串,也可以用元组。
  • 方法 get(key,default=xxx) a['key']这种方法如果没有找到会报错,a.get('key')返回设定默认值
  • pop 删除元素弹出并返回key对应值
  • in
  • keys values items返回键、值、键值对元组
In [62]:
d={'a':1,"b":2,('cangzhou','beijing'):'220KM'}
d2=dict([("c",3),('d',4),(5,555)])
d2['e']=5
d['a']=111
del d2['c']
print d,d2,d['a'],d.update(d2),d[('cangzhou','beijing')]
print d.pop('d')
print d,d2.get('a')
print d.keys(),d.values(),d.items()
{'a': 111, 'b': 2, ('cangzhou', 'beijing'): '220KM'} {'e': 5, 'd': 4, 5: 555} 111 None 220KM
4
{'a': 111, 'b': 2, 'e': 5, ('cangzhou', 'beijing'): '220KM', 5: 555} None
['a', 'b', 'e', ('cangzhou', 'beijing'), 5] [111, 2, 5, '220KM', 555] [('a', 111), ('b', 2), ('e', 5), (('cangzhou', 'beijing'), '220KM'), (5, 555)]

集合

  • 集合是无序的,只能放不可变对象
  • set() set([1,2,3]) {1,2,3} 创建空集合只能用set(),因为{}是字典
  • 操作 并:a.union(b)或者a|b,交:a.intersection(b)或a&b,差:a.difference(b)或a-b只在a不在b,对称差a.symmetric_difference(b)或a^b在a或b中,但不同时在ab中
  • 包含 b.issubset(a)b是不是a的子集或者b<=a;a.issuperset(b) 或者a>=b。方法只能用来测子集,运算符可以用来判断真子集。
  • 集合方法 添加单个add 添加多个update 删除,报错:remove() 删除,不报错:dicard() 任意弹出并返回:pop() difference_update(B)去除所有属于B的元素
In [102]:
s=set([1,2,3,4,5,6])
s2={5,6,7,8,9,10}
print s.union(s2),s|s2
print s.intersection(s2),s&s2
print s.difference(s2),s-s2
print s2.difference(s),s2-s
print s.symmetric_difference(s2),s^s2
print {1,2,3,4,5,6}.issubset(s),{1,2,3,4,5}.issuperset(s),{1,2,3}<=s,{1,2,7}<s
s.add(7),s.update({8,9}),s.discard(10),s.remove(9)
print s,s.pop(),s.pop(),s.pop(),s.pop(),s
set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
set([5, 6]) set([5, 6])
set([1, 2, 3, 4]) set([1, 2, 3, 4])
set([8, 9, 10, 7]) set([8, 9, 10, 7])
set([1, 2, 3, 4, 7, 8, 9, 10]) set([1, 2, 3, 4, 7, 8, 9, 10])
True False True False
set([1, 2, 3, 4, 5, 6, 7, 8]) 1 2 3 4 set([5, 6, 7, 8])

不可变集合frozenset

  • s=frozenset([1,2,3])不可变集合用作字典的键,由于集合不分顺序,所以可变集合影响查询。
In [105]:
s=frozenset([1,2])
print s
frozenset([1, 2])

赋值机制

  • id(x)返回x的内存地址,is判断是否同一事物
In [148]:
def f():
    pass
a=123
a2=122
a3=122#122相同值可能优化
print a2 is a3
b=1222L
b2=1222L#L值不会优化
print b is b2
print id(f),id(a),id(a2),id(a3),id(b),id(b2)
True
False
62596912 5362008 5362020 5362020 62637120 62636976
1
2
3
4
5

判断语句

  • if ccc:pass elif ccc:pass else:pass
  • and or not
  • 大部分表达式的值视为True,但是None False 0 空字符串、字典、列表、集合视为False

循环

  • while 循环到条件不满足,空容器视为false所以可用于循环读取容器中的元素
  • for 遍历所有元素 xrange优于range
  • continue break else语句,当循环正常结束时else执行,当break时else不执行
In [ ]:
i=1
while i<10:
    if i >5:
        break
    print i
    i+=1
else:
    print 'END'

列表推导式

  • 列表推导式创建列表、集合、字典
In [152]:
print [x**2 for x in xrange(10) if x<6]
print {x**2 for x in xrange(10) if x>5}
print {x:x**2 for x in xrange(10) if x<6}
[0, 1, 4, 9, 16, 25]
set([64, 49, 36, 81])
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

函数

  • *args不定参数 **kwargs 字典键值对传参数
  • for a in args:
  • for arg,value in kwargs.items():
  • 返回多个值,元组
  • 元组做参数传入时用* 字典做参数传入时用**
  • map方法生成序列,map(fun,seq)fun作用于每个seq元素,返回列表,不管seq是何种类型。
  • 序列类型亦可以作为参数传入seq
In [167]:
def f(*args,**kwargs):
    for a in args:
        print a
    for k,v in kwargs:#.items():
        print k,w
a=(1,2,3)
b={'name':'zhangsan','age':23}
f(a,b)

def add1(x):
    return x+1
def add2(x,y):
    return x+y
map(add,(2,3))
map(add2,(2,3),(4,5))#sequence 
(1, 2, 3)
{'age': 23, 'name': 'zhangsan'}
Out[167]:
[6, 8]

模块和包

  • 导入模块时,会执行一遍模块中所有内容,重新import不再执行,需要强制reload(),如果需要当脚本也作模块,需要name=='main'
  • 加from可以直接使用,不用前缀
  • 包需要加init.py文件

异常

  • try: pass except (e1,e2,e3)|不指定,所有异常|Exception:pass finally:pass
  • 自定义异常 class enError(ValueError):pass rais enError('xxxx') except: enError:pass

警告

In [176]:
import warnings
print dir(warnings)
['WarningMessage', '_OptionError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_getaction', '_getcategory', '_processoptions', '_setoption', '_show_warning', 'catch_warnings', 'default_action', 'defaultaction', 'filters', 'filterwarnings', 'formatwarning', 'linecache', 'once_registry', 'onceregistry', 'resetwarnings', 'showwarning', 'simplefilter', 'sys', 'types', 'warn', 'warn_explicit', 'warnpy3k']

文件读写

  • read 所有内容 readlines 每行作为列表
  • a 追加 w+ 读写 b二进制
  • write(os.urandom(16)) repr(f.read())
  • 换行 不同os下\r \r\n \n 三种 U选项
  • with 结束后调用close方法

05.Python进阶

sys模块

In [202]:
import sys
print sys.argv,sys.exc_info(),sys.stdin,sys.path,sys.platform,sys.version,sys.version_info
#sys.exit(0)
['D:\\Program Files\\Anaconda2\\lib\\site-packages\\ipykernel\\__main__.py', '-f', 'C:\\Users\\Administrator.SKY-20171103JGR\\AppData\\Roaming\\jupyter\\runtime\\kernel-f2b41b45-4e6f-4e62-911d-9c5167174200.json'] (None, None, None) ', mode 'r' at 0x004ED020> ['', 'D:\\Program Files\\Anaconda2\\python27.zip', 'D:\\Program Files\\Anaconda2\\DLLs', 'D:\\Program Files\\Anaconda2\\lib', 'D:\\Program Files\\Anaconda2\\lib\\plat-win', 'D:\\Program Files\\Anaconda2\\lib\\lib-tk', 'D:\\Program Files\\Anaconda2', 'D:\\Program Files\\Anaconda2\\lib\\site-packages', 'D:\\Program Files\\Anaconda2\\lib\\site-packages\\Sphinx-1.5.1-py2.7.egg', 'D:\\Program Files\\Anaconda2\\lib\\site-packages\\pyinstaller-3.2.1-py2.7.egg', 'D:\\Program Files\\Anaconda2\\lib\\site-packages\\setuptools-27.2.0-py2.7.egg', 'D:\\Program Files\\Anaconda2\\lib\\site-packages\\baidu_aip-2.0.0.1-py2.7.egg', 'D:\\Program Files\\Anaconda2\\lib\\site-packages\\win32', 'D:\\Program Files\\Anaconda2\\lib\\site-packages\\win32\\lib', 'D:\\Program Files\\Anaconda2\\lib\\site-packages\\Pythonwin', 'D:\\Program Files\\Anaconda2\\lib\\site-packages\\IPython\\extensions', 'C:\\Users\\Administrator.SKY-20171103JGR\\.ipython'] win32

操作系统交互

  • getcwd curdir listdir remove unlink removedirs chdir rename renames listdir mkdir makedirs
  • os.linesep,os.sep,os.pathsep 换行 路径分隔符 环境变量分隔符
  • os.environ 环境变量
  • os.path模块,为了列出不同os下path规范而引出os.path模块 isfile isdir exists isabs split join abspath dirname basename splitext expanduser
In [26]:
import os
print os.getcwd(),os.curdir,os.listdir(os.curdir)
print os.linesep,os.sep,os.pathsep
print os.environ
print os.path.isfile('a.txt'),os.path.isdir('./cookie'),os.path.exists('./cookie'),\
os.path.isabs('./cookie'),os.path.split('.'),os.path.abspath('.')
f = os.path.join(os.path.abspath('.'),'argv.py')
print os.path.split(f),os.path.dirname(f),os.path.basename(f),os.path.splitext(f)
 D:\www.gongqingkui.cn\pythoncodestudy . ['.git', 'zipline', 'learnPythonTheHardWay', 'ppTest', 'aerfa', 'web', 'cookie', 'standardLib', 'tushare', 'requests', 'caiwuchuli', 'websiteUpdateAlert', 'HTSQL', 'user.db', 'argv.py', 'dist', 'findfat', '.gitignore', 'cangzhoujianyu', 'rss', 'multiprocessing', 'sched.py', 'sched.pyc', 'build', 'manual', 'findfat_tkinter_rubbishProcess.ipynb', 'funds2doc2kpw.py', 'serial', 'datetime', 'unittest', 'email', 'records_pythonLib_study.ipynb', 'GPIOTEST.txt', '.project', '.settings', '.pydevproject', 'pyautogui', 'selenium', 'loggingTest', 'tkinter', 'wind', 'ipythonnotebook', '.ipynb_checkpoints', 'numpy', 'matplotlib', 'sqlserverPython', 'pyinstallerTest', 'python4finance', 'selenium2', 'weixin', 'PythonQRC', 'QRCPython.ipynb']

\ ;
{'TMP': 'C:\\Users\\ADMINI~1.SKY\\AppData\\Local\\Temp', 'COMPUTERNAME': 'SKY-20171103JGR', 'USERDOMAIN': 'SKY-20171103JGR', 'PSMODULEPATH': 'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\', 'COMMONPROGRAMFILES': 'C:\\Program Files (x86)\\Common Files', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 23 Stepping 10, GenuineIntel', 'PROGRAMFILES': 'C:\\Program Files (x86)', 'PROCESSOR_REVISION': '170a', 'SYSTEMROOT': 'C:\\Windows', 'PATH': 'D:\\Program Files\\Anaconda2\\Library\\bin;D:\\Program Files\\Anaconda2\\Library\\bin;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;d:\\Program Files\\Git\\cmd;D:\\Program Files\\Vim\\vim74;.;D:\\Program Files\\Anaconda2;D:\\Program Files\\Anaconda2\\Scripts;D:\\Program Files\\Anaconda2\\Library\\bin;.;D:\\r\xc8\xed\xbc\xfe', 'CLICOLOR': '1', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', '#ENVKKPRBC_CMDILNE': '', 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe', 'LANG': 'zh_CN', 'TERM': 'xterm-color', '#ENVTSLOGTSLOG2728': '3249792', 'TEMP': 'C:\\Users\\ADMINI~1.SKY\\AppData\\Local\\Temp', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'PROCESSOR_ARCHITECTURE': 'x86', 'ALLUSERSPROFILE': 'C:\\ProgramData', 'SHELLLAUNCH{A81BA54B-CCFE-4204-8E79-A68C0FDFA5CF}': 'ShellExt', 'LOCALAPPDATA': 'C:\\Users\\Administrator.SKY-20171103JGR\\AppData\\Local', 'HOMEPATH': '\\Users\\Administrator.SKY-20171103JGR', 'JPY_INTERRUPT_EVENT': '1188', 'PROGRAMW6432': 'C:\\Program Files', 'USERNAME': 'Administrator', 'LOGONSERVER': '\\\\SKY-20171103JGR', 'PROMPT': '$P$G', 'WINDOWS_TRACING_FLAGS': '3', 'JPY_PARENT_PID': '1136', 'PROGRAMDATA': 'C:\\ProgramData', '#ENVTSLOGXMEDIALIBRARY2728': '223300128', '#ENVTSLOGSSS2728': '3349424', 'MPLBACKEND': 'module://ipykernel.pylab.backend_inline', 'GIT_PAGER': 'cat', 'SESSIONNAME': 'Console', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC', 'ASL.LOG': 'Destination=file', 'FP_NO_HOST_CHECK': 'NO', 'WINDIR': 'C:\\Windows', 'WINDOWS_TRACING_LOGFILE': 'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log', 'HOMEDRIVE': 'C:', 'PAGER': 'cat', 'SYSTEMDRIVE': 'C:', '#ENVTSLOGRBCSHELLEXT2728': '3249152', 'NUMBER_OF_PROCESSORS': '2', 'APPDATA': 'C:\\Users\\Administrator.SKY-20171103JGR\\AppData\\Roaming', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_ARCHITEW6432': 'AMD64', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'OS': 'Windows_NT', 'PUBLIC': 'C:\\Users\\Public', 'IPY_INTERRUPT_EVENT': '1188', 'USERPROFILE': 'C:\\Users\\Administrator.SKY-20171103JGR'}
False True True False ('', '.') D:\www.gongqingkui.cn\pythoncodestudy
('D:\\www.gongqingkui.cn\\pythoncodestudy', 'argv.py') D:\www.gongqingkui.cn\pythoncodestudy argv.py ('D:\\www.gongqingkui.cn\\pythoncodestudy\\argv', '.py')

csv和csv模块

  • numpy.loadtext pandas.read()
  • import pandas
  • df=pandas.readcsv('f',index_col=0)
  • df['quantity']*df['price']
In [41]:
import csv
data=[[1,2,3],[4,5,6]]
with open('csvtest.csv','wb') as fp:
    #w = csv.writer(fp,delimiter='|')
    w = csv.writer(fp)
    w.writerows(data)
    
r=csv.reader(open('csvtest.csv'))
for row in r:
    print row#row[2]
['1', '2', '3']
['4', '5', '6']

正则表达式和re

方法

  • match search 寻找第一个匹配 返回match对象或者None,match匹配头,search匹配整个字串中字串
  • findall finditer(p,s) 返回所有对象,迭代器
  • re.split(p,s)p指定内容对S进行分割
  • sub(p,r,s)匹配内容替换
  • compile(p)生成P对象,该对象有匹配 替换 分割字串方法

正则规则

  • s
    • .换行之外 \w数字字母 \d数字 \s空白字符相当于[\t\n\t\f\v]
    • []集合 ()整体 |或 ^头
    • *匹配前面零次或者多次 +一次或多次 {m}次 {m,} {m,n}
    • 逃逸字符 \ raw字串 r开头 p = r'\'
  • #print r.split() #print r.sub('a','*') TODO 有问题
In [87]:
import re
s='The quick brown fox jumps over the lazy dog'
print re.match('\w*',s).group(),re.match('.',s).group(),\
re.search('\w*',s).group(),re.search('.',s).group(),\
re.findall('\w*',s),re.split('[a-d]',s),re.sub('[a-d]','*',s)
for r in re.finditer('\w*',s):
    pass
    #print r.group()
print '*'*20
r=re.compile('\w*')
print r.search(s).group(),r.match(s).group()
#print r.split()
#print r.sub('a','*')
 The T The T ['The', '', 'quick', '', 'brown', '', 'fox', '', 'jumps', '', 'over', '', 'the', '', 'lazy', '', 'dog', ''] ['The qui', 'k ', 'rown fox jumps over the l', 'zy ', 'og'] The qui*k *rown fox jumps over the l*zy *og
********************
The The

datatime

In [129]:
import datetime as dt
d1 = dt.date(2018,3,11)
d2 = dt.date.today()
print d1,d1.strftime('%A %d-%m-%y'),d2-d1,d1-d2,type(d2-d1),dt.date.today()

t1=dt.time(12,11,2,30)
t2=dt.time(12,56,1,34)
print t1.strftime('%I:%m:%p')
#不支持-

dt1 = dt.datetime.now()
dt2 = dt.datetime(2018,3,1,12,11,12,45)
td = dt.timedelta(1,12,51,51,1)
print dt1-dt2,dt1+td,dt1.strftime('%a%A%W%b%B%d%H%I%j%m%M%U%W%Y%y')
#字串创建dt对象
dt3=dt.datetime.strptime('2/10/01','%m/%d/%y')
2018-03-11 Sunday 11-03-18 1 day, 0:00:00 -1 day, 0:00:00  2018-03-12
12:01:PM
11 days, 9:47:05.194955 2018-03-13 21:59:29.246051 MonMonday11MarMarch12210907103581011201818

sql db之sqlite3

  • execute executemany rollback fetchall close
In [141]:
import sqlite3 as db
c=db.connect('db.sqlite')
cw = c.cursor()
sql = 'drop table users'
cw.execute(sql)
sql = 'create table users(uid int auto_increment primary key,name varchar(32))'
cw.execute(sql)
c.commit()
sql = 'insert into users values(1,"zhang")'
cw.execute(sql)
sql = 'select * from users'
cw.execute(sql)
rows = cw.fetchall()
for r in rows:
    print r
c.commit()
c.close()
(1, u'zhang')

对象关系映射

  • DB中record可对应python object,用sqlalchemy实现
In [164]:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String

base = declarative_base()
class user(base):
    __tablename__ = 'users'
    uid = Column(Integer,primary_key=True)
    name = Column(String)
    
userA = user(uid=3,name='qian')

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///db.sqlite')
session = sessionmaker(bind=engine)
Session = session()
#Session.add(userA)
#Session.commit()
for row in Session.execute('select * from users'):
    print row
    
for u in Session.query(user).filter(user.uid<=2):
    print u.uid,u.name
(1, u'zhang')
(2, u'zhao')
(3, u'qian')
1 zhang
2 zhao

函数进阶

  • 函数是一种基本类型,意味着函数可作为参数,字典。
  • 参数传递:
    • 引用传递,修改引用的值,外面的值也改变,但是若该变成新值,外面的值不变。
    • 函数参数绑定发生在函数定义时,伺候每次调用默认参数就是用同一引用
In [168]:
a=[1,2]
def fun(a):
    a[0]+=1
fun(a)
fun(a)
print a
[3, 2]
  • 高阶函数 函数做参数,返回函数的函数就是高阶函数
    • map(f.seq)f作用于seq序列每个元素上去
    • filter(f.seq)每个seq元素返回所有f(s)位True的列表
    • reduce(f,seq)接受f(x,y)对每个seq对象合并两个元素
  • 匿名函数 -lambda var:exp eg. print map(lambda x:x**2,range(5))
In [176]:
def f(c):
    return c*2

def f2(c):
    return c>=5

def f3(x,y):
    return x*y

a='sos'
map(f,a)
filter(f2,xrange(10))
reduce(f3,xrange(1,10))

map(lambda x:x*3,xrange(10))
Out[176]:
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
  • global 修改全局变量需要在函数内加上
  • 递归 base case ; recurssive case;

迭代器

  • 如果需要引脚数据,需要将迭代器放入enumerate中产生(index,value)元组
  • iter方法

生成器

yield
In [185]:
def f():
    for i in xrange(10):
        yield i

def f2():
    for i in xrange(10):
        yield i,i*2
        
for f in f():
    print f,
for k,v in enumerate(f2()):
    print k,v
 0 1 2 3 4 5 6 7 8 9 0 (0, 0)
1 (1, 2)
2 (2, 4)
3 (3, 6)
4 (4, 8)
5 (5, 10)
6 (6, 12)
7 (7, 14)
8 (8, 16)
9 (9, 18)

with语句和上下文管理器

  • 处理文件、数据库、县城、网络编程等资源
  • Contentlib模块中closing方法 with closing(open()) as f:
  • 修饰符,上文模块中引入 contentmangager用于修饰函数实现with功能

修饰符

  • dir(f)
  • 修饰符接受一个函数作为输入,通常输出也是一个函数,可以利用它生成一个新的函数。

    def dec(f): return f def foo(x):print x foo=dec(foo) 或者@dec def foo(x) print x

  • 支持链式使用修饰符
In [196]:
def d1(f):
    print 'd1pre'
    return f

def d2(f):
    print 'd2pre'
    return f

@d1
@d2
def f(x):
    print 'fpre'
    print x

f('gong')
foo=d2(d1(f('hahaha')))
d2pre
d1pre
fpre
gong
fpre
hahaha
d1pre
d2pre

修饰符的使用

- classmethod 对象方法转为类方法

operator

  • operator提供+-*/等的函数版本,方便调用 sorted(list,key=op.itemgetter(1)) sorted(list,key=lambda x:len(x[0]))
  • functools 函数相关模块
  • itertools 迭代对象相关 eg.排列组合生成器 3!permutations C3,2 combinations 分析groupby
In [213]:
import operator as op
print reduce(op.add,xrange(10))

import itertools
#相当于3!
for i in itertools.permutations((2,3,4)):
    print i
#相当于C3,2
for i in itertools.combinations((2,3,4),2):
    print i
45
(2, 3, 4)
(2, 4, 3)
(3, 2, 4)
(3, 4, 2)
(4, 2, 3)
(4, 3, 2)
(2, 3)
(2, 4)
(3, 4)

有用的工具

pprint

  • 打印python对象,pretty printer缩写,import pprint pprint.pprint(xx)

pickle

  • 序列化python 对象,cpickle引入的 话,try:import cPickle as pcikle except: import pickle
  • pickle.dumps()对象转成字符串 pickle.loads()反之
  • dumps(obj,fileobj,protool)存入文件 load(fileobj)反之

json

  • json.loads()字串读入 json.dumps(xx)python对象编程json对象
  • dump(obj,file)对象存入文件 load(f)反之

glob

  • 文件匹配 *多个 ?任意多个 []范围内

shutil

  • 高级文件操作 shutil.copy(src,dst) copyfile不复制权限 renames copytree removedirs rmtree move make_archive(basename,format,rootdirs)

gzip zipfile tarfile

  • zlib.compress(str) zlib.decopress(str)
  • gzip.open(f,'wb') as f f.write(xx)

logging

  • logging.critical(msg) error warning infor debug

string

  • punctuation letters lower hexdigits

collections

  • 更多数据结构 import collections
  • 计数 Counter(sentense.translate(None,punctuation.lower().split())
  • 双端队列 deque pop append appendleft popleft
  • 有序字典 OrderedDict(dict)
  • 默认值字典 defaultdict(dict)

requests

  • http for humans
  • r = requests.get(url) post head
  • p={'key':'va','k':'wv'}requests.get(url,params=p)
  • r.text r.url r.encoding r.json r.encoding='utf-8'
  • r.headers['Content-Type']

:# 数据结构

数据结构定义

数组 队列 栈 集合 树 图 集合 字典 结构体

操作

新建 空建,带值,默认值,转化建立

增 增一个 增多个

删 删一个 删多个 删全部

改 改一个 改多个 改全部

引用 单个 多个 切片

查位置 单个 多个 全部

操作 连接 排序 销毁 求长度 是否在 遍历

自己的笔记

sched

In [12]:
#%%writefile sched.py
from sched import *
import time

def echo(st):
    print '*'*10+st+'*'*10
s = sched.scheduler(time.time,time.sleep)
s.enter(3,1,echo,('hello',))
s.enter(3,1,echo,('li',))
s.run()
**********hello**********
**********li**********zhong

你可能感兴趣的:(具体技术,python)