Python 絕對簡明手冊 -- zsp007@gmail.com ::-- ZoomQuiet [2006-09-15 04:35:33]
1. Py2.5 絕對簡明手冊
簡述
zuroc主動在列表中分享
PYthon絕對簡明手冊,初學必備!
版本:0.2 beta
作者:張沈鵬
參考:python2.5中文教程
感謝:Zoom.Quiet limodou
我的技術Blog 我的C++Blog 我的文學Blog
1.1. 語法
1.1.1. if
Toggle line numbers
1 x=int(raw_input("Please enter an integer:"))
2 if x<0:
3 print 'Negative Number'
4 elif x==0:
5 print 'Zero'
6 else:
7 print 'Positive Number'
1.1.2. for
#如果要修改a的內容,則用a的副本循環,如:
for x in a[:] :
.....................
Toggle line numbers
1 >>>range(10,0,-3)
2 [10,7,4,1]
3 a=['cat','door','example']
4 for i in range(len(a)):
5 print i,a[i]
break,continue 用法和C++中類似
1.1.3. pass
while True:
pass #忽略,什么也不做
Toggle line numbers
1 def fib(n=1000):
2 """這里給函數寫文檔注釋"""
3 a,b=0,1
4 while b<n:
5 print b
6 a,b=b,a+b
#函數可以重命名,如
1.1.4. in
1.1.5. 參數格式 **para
#參數格式為 **para 表示接受一個字典,為 *para 表示接受一個元組
Toggle line numbers
1 def test(para1,*args,**dic):
2 print para1
3 for arg in args : print arg
4 keys=dic.keys()
5 keys.sort()
6 for key in keys:print key ,':',dic[key]
1.1.6. Lambda函數
-
Toggle line numbers
1 def make_incrementor(n):
2 return lambda x: x+n
3 f=make_incrementor(n)
4 >>>f(0)
5 42
6 >>>f(1)
7 43
1.1.7. List的函數
append(x) 追加到鏈尾
extend(L) 追加一個列表
insert(i,x) 在位置i插入x
remove(x) 刪除第一個值為x的元素,如果不存在會拋出異常
pop([i]) 返回并刪除位置為i的元素,i未給定時默認作用在最后一個元素.[i]表示i為可選的
index(x) 返回第一個值為x的元素,不存在則拋出異常
count(x) 返回x出現的次數
sort() 排序
reverse() 翻轉,反轉
filter(function函數 , sequence序列) 返回sequence中使filer為true的
map(function,sequence,[sequence...]) 返回新的sequence,序列中值為對每個元素分別調用function.
reduce(function,sequence,[init]) 返回一個單值為,計算步驟為 :
- 第1個結果=function(sequence[0],sequence[1])
- 第2個結果=function(第1個結果,sequence[2])
- 返回最后一個計算得值
- 如果有init,則先調用
function(init,sequence[0]) sequence只有一個元素時,返回該元素,為空時拋出異常.
1.1.8. 列表推導式
freshfruit=[' banana ',' loganberry ']
>>>[weapon.strip() for weapon in freshfruit]
['banana','loganberry']
vec=[2,4,6]
>>>[3*x for x in vec if x>3]
[12,18]
>>>[(x,x**2) for x in vec] #一個元素一定要是一個sequence,而
[x,x**2 for x in vec]是錯誤的
[(2,4),(4,16),(6,36)]
vec2=[4,3,-9]
[x*y for x in vec for y in vec2]
[vec[i]+vec2[i] for i in range(len(vec))]
[str(round(355/113.0,i)) for i in range(1,6)] #str()是轉換類型為可以打印的字符
1.1.9. del
Toggle line numbers
1 a=[1,2,3,4,5,6]
2 del a[0]
3 >>>a
4 [2,3,4,5,6]
5 del a[2:4]
6 >>>a
7 [2,3,6]
8 del a[:]
9 >>>a
10 []
11 del a
12 >>>a
拋出異常
1.1.10. 元組
t=1234,5567,'hello'
x,y,z=t #拆分操作可以應用于所有sequence
>>>x
1234
u=t,(1,2,3)
>>>u
((1234,5567,'hello'),(1,2,3))
empty=() #空元組
singleton='hi', #單個元素的元組
1.1.11. set
set(集合):無序不重復的元素集
Toggle line numbers
1 basket = ['apple','orange','apple','pear','apple','banana']
2 fruit=set(basket)
3 >>>fruit
4 set(['orange', 'pear', 'apple', 'banana'])
5 >>>'orange' in fruit
6 True
7 a=set('abracadabew')
8 >>>a
9 set(['a', 'c', 'b', 'e', 'd', 'r', 'w'])
10 b=set('wajgwaoihwb')
11 >>> b
12 set(['a', 'b', 'g', 'i', 'h', 'j', 'o', 'w'])
13 >>> a-b
14 set(['c', 'r', 'e', 'd'])
15 >>> a|b
16 set(['a', 'c', 'b', 'e', 'd', 'g', 'i', 'h', 'j', 'o', 'r', 'w'])
17 >>> a&b
18 set(['a', 'b', 'w'])
19 >>>a^b
20 set(['c', 'e', 'd', 'g', 'i', 'h', 'j', 'o', 'r'])
=== dict ===
字典:關鍵字為不可變類型,如字符串,整數,只包含不可變對象的元組.列表等不可以作為關鍵字.如果列表中存在關鍵字對,可以用dict()直接構造字典.而這樣的列表對通常是由列表推導式生成的.
Toggle line numbers
1 tel={'jack':4098,'sape':4139}
2 tel['guido']=4127
3 >>> tel
4 {'sape': 4139, 'jack': 4098, 'guido': 4127}
5 >>>tel['jack']
6 4098
7 del tel['sape']
8 >>>tel.keys()
9 ['jack', 'guido']
10 >>>tel.has_key('jack')
11 True
12 knight={'gallahad':'the pure','robin':'the brave'}
13 for k,v in knight.iteritems():
14 print k,v
輸出:
enumerate()返回索引位置和對應的值
輸出: 0 tic
1 tac
2 toe
1.1.12. zip
zip用于多個sequence的循環
Toggle line numbers
1 questions=['name','quest','favorite color']
2 answers=['lancelot','the holy grail','blue']
3 for q,a in zip(questions,answers):
4 print 'What is your %s ? It is %s.'%(q,a)
輸出:
What is your name ? It is lancelot.
What is your quest ? It is the holy grail.
What is your favorite color ? It is blue.
1.1.13. reversed反向循環
輸出:
3
2
1
1.1.14. sorted排序
1.1.15. sequence比大小
list<string<tuple(因為字母表中l在s前...)
同類比大小按照字典序
1.1.16. 導入模塊
模塊的查找路徑
1.當前的目錄
2.環境變量PYTHONPATH所指的目錄列表
3.python解釋器的安裝目錄
如將代碼保存上述的一個目錄中的的fibo.py文件中,便可以
如果想直接使用fibo.function可以重命名這個函數,如
也可以
甚至可以form fibo import *
可以 form 包.子包.模塊 imort 函數
然后就直接使用該函數,不需要加前綴
1.1.17. 包
引用推薦寫法為
form 包 import 模塊
幾個功能類似的模塊可以組合成一個包,
比如一個可以處理.wav,.mp3,.wma等音頻文件的有類似如下結構:
Sound/
__init__.py
Formats/
__init__.py
wavread.py
wavwrite.py
mp3read.py
mp3write.py
wmaread.py
wmawrite.py
Effects/
__init__.py
echo.py
surround.py
reverse.py
只有當init.py存在時python才將該文件夾視為一個包,該文件可以為空文件 一般在init.py文件中定義一個all列表,包含要import *時要導入的模塊. 如Sound/Effects/init.py可以有如下內容
__all__=["echo","surround","reverse"]
包的作者在發布包時可以更新這個列表,也可以根據需要讓某個模塊不支持import *
對于包中同一個文件夾下的模塊可以把
form 包.子包 imort 模塊
簡寫為 imort 模塊
1.1.18. 格式化輸出
for x in xrange(1,11):
print repr(x).rjust(2),repr(x*x).rjust(3)
#repr是將變量類型轉換為可以被編譯器處理的文字格式
#rjust是調整寬度為參數個字符,r表示右對齊;ljust為左對齊,ljust(n)[:n]可
以截斷輸出;center為居中
#zfill()可以向數值表達式的左側填充0
1.1.19. 等效代碼
for x in xrange(1,11):
print '%2d %3d' % (x,x*x)
#%10s 表示用str轉化為字符串
#小數輸出如 %5.3f
對于字典可以用變量名來直接格式化,如:
>>>table={'Sjoerd':4127,'Jack':4098,'Dcab':8637678}
>>>print 'Jack:%(Jack)d; Sjoerd:%(Sjoerd)d; Dcab:%(Dcab)d' %
table
Jack:4098; Sjoerd:4127; Dcab:8637678
同時,函數vars()返回包含所有變量的字典,配合使用,無堅不摧!
1.1.20. 讀寫文件:
f=open('/tmp/hello','w')
#open(路徑+文件名,讀寫模式)
#讀寫模式:r只讀,r+讀寫,w新建(會覆蓋原有文件),a追加,b二進制文件.常用模式
如:'rb','wb','r+b'等等
f.read([size]) size未指定則返回整個文件,如果文件大小>2倍內存則有問題.f.read()讀到文件尾時返回""(空字串)
file.readline() 返回一行
file.readline([size]) 返回包含size行的列表,size 未指定則返回全部行
for line in f: #交換通道
f.write("hello\n") #如果要寫入字符串以外的數據,先將他轉換為字符串.
f.tell() 返回一個整數,表示當前文件指針的位置(就是到文件頭的比特數).
f.seek(偏移量,[起始位置])
用來移動文件指針
偏移量:單位:比特,可正可負
起始位置:0-文件頭,默認值;1-當前位置;2-文件尾
f.close() 關閉文件
1.1.21. pickle
pickle 序列化/保存對象/封裝
pickle.dump(x,f) #把文件對象f保存到x變量中
x=pickle.load(f) #還原這個對象
try:
except 異常類型:
#如果有多個異常類型,可以將他們放在括號()中
#如except(RuntimeError,TypeError,NameError):
最后一個異常名可以省略異常類型,作為通配項將所有異常pass.慎用!!!
在except后可以包含一個else
raise可以拋出異常,同時可以附帶異常參數
try:
- rasie Exception('message1','message2') #只有一個參數時也可以這樣寫rasie Exception,'message1'
except Exception,inst:
如果拋出異常沒有指定參數,則捕獲異常時的參數包含的是該異常的默認信息
>>>try:
Handling run-time error:integer division or modulo by zero
自定義異常:慣例是以Error結尾的類,同類的異常一般派生自同一個基類,基類異常可以匹配派生類異常
class MyError(Exception):
-
def init(self,value):
def str(self):
try:
except MyError,e:
- print 'My exeception occurred,value',e.value
>>>
My exeception occurred,value 4
finally:和C++中類似,即使是break,continue或return后一樣會執行。一般用于釋放資源,如文件,網絡連接。
def divide(x,y):
with #with可以幫助你自動釋放資源,下一個版本可用
with open('myfile.txt') as f:
#該文件會自動被釋放
1.1.22. 初識類
class ClassName:
-
def init(self):
- "構造函數,可以初始化變量,可以有參數" #可以通過self調用當前類的函數和數據 self.data=[]
#創建類實例
x=ClassName()
#給類的方法重命名
xf=ClassName.f
1.1.22.1. 類繼承
class DerivedClassName(BassClassName):
- ...................................
如果基類定義在另一個模塊中, 要寫成
modname.BaseClassName
派生類的函數會覆蓋基類的同名函數,如果想擴充而不是改寫基類的函數,可以這樣調用基類函數
BaseClassName.methodname(self,arguments)
注意:該基類要在當前全局域或被導入
1.1.22.2. 多重繼承
類多繼承//小心使用
class DerivedClassName(Base1,Base2,Base3):
.................
對于一個函數的解析規則是深度優先,先是Base1,然后是Base1的基類,諸如此類.
1.1.23. Iterators 迭代器
for element in [1,2,3]:
for key in {'one':1,'two':2}:
for line in open("my.txt"):
在容器中定義next()逐一返回元素,并在迭代完成時拋出StopIteration異常,然后定義iter()返回self,便可以for...in循環
用Generators(生成器)可以快速生成一個序列,在調用next()時依次返回序列中的值.
def reverse(data):
- for index in range(len(data)-1,-1,-1):
#yield會自動創建next()和iter(),每次調用next()時yield會進行下一步循環,并在yield處返回值
1.1.24. 生成器表達式
生成器表達式:類似于沒有中括號的列表推導式,可用在參數中
>>>sum(i*i for i in range(10))
285
>>>xvec=[10,20,30]
>>>yvec=[7,5,3]
>>>sum(x*y for x,y in zip(xvec,yvec))
>>>from math import pi,sin
>>>sine_table=dict((x,sin(x*pi/180) for x in range(1,91))
>>>unique_words=set(word for line in page for word in line.split())
>>>data='golf'
>>>list(data[i] for i in range(len (data)-1,-1,-1))
['f','l','o','g']
1.2. 常用函數不完全手冊
dir(模塊) #來獲取模塊的函數/變量列表
help(模塊/函數) #獲取相關的幫助
模塊:os
例:
import os
os.getcwd() #當前腳本的工作目錄
os.chidr() #改變當前工作目錄
模塊:shutil
例:
import shutil
shutil.copyfile('data.txt','archive.txt')
shutil.move('/build/a.txt','b.txt')
模塊:glob
生成文件列表,支持通配符
例:
import glob
>>>glob.glob('*.py')
['primes.py','random.py','quote.py']
模塊:sys
提供命令行參數,錯誤輸出重定向和腳本終止
例:
命令行參數
如執行python demo.py one,two,three后
import sys
print sys.argv
會輸出
['demo.py','one','two','three']
終止腳本
sys.exit()
錯誤輸出重定向,可以在stdout被重定向時顯示錯誤信息
>>>sys.stderr.write('Warning , log file not found starting a new one\n')
Warning , log file not found starting a new one
模塊:re
字符正值表達式匹配
例:
import re
>>>re.findall(r'\bf[a-z]*','which foot or hand fell fastest')
['foot','fell','fastest']
>>>re.sub(r'(\b[a-z]+)\l',r'\l','cat in the hat')
'cat in the hat
模塊:math
為浮點運算提供了底層C函數庫的訪問
例:
>>>math.cos(math.pi/4.0)
0.70710678118654757
>>>math.log(1024,2)
10.0
模塊:random
生成隨機數
例:
import random
>>>random.choice(['apple','pear','banana'])
'apple'
>>> random.sample(xrange(100),10) #隨機值不會重復
[20,42,12,44,57,88,93,80,75,56]
>>>random.random()
0.26676389968666669
>>> random.randrange(10)
7
模塊:urblib2
打開url地址
例:
for line in urllib2.urlopen('http:\\www.python.org\')
模塊:smtplib
發送電子郵件
例:
sever=smtplib.smtp('localhost')
sever.sendmail('zsp007@gmail.com','zuroc@163.com')
"""TO:zsp007@gmail.com
From:zuroc@163.com
"""
sever.quit()
模塊:datetime
時間日期相關算法以及格式化輸出
例:
from datetime import date
now=date.today
>>>now
datetime.date(2006, 9, 13)
>>>now.strftime("%m-%d-%y . %d %b %Y is a %A on the %d day of %B . ")
'09-13-06 . 13 Sep 2006 is a Wednesday on the 13 day of September . '
birthday=date(1986,6,30)
age=now-birthday
>>> age.days
7380
模塊:zipfile / tarfile
數據打包和壓縮,支持格式:zlib,gzip,bz2,zipfile和tarfile
例:
import zlib
s="which which which which"
>>>len(s)
23
>>>len(t)
16
>>>zlib.decompress(t)
"which which which which"
>>>zilb.crc(32)
-487390043
模塊:timeit
性能測試
例:
from timeit import Timer
#Timer的第一個參數是要測試時間的語句,第二個參數是初始化
#timeit的參數是測試語句的執行次數,默認執行1000000次
>>> Timer('t=a;a=b;b=t','a=1;b=2').timeit()
0.31399409701512582
>>> Timer('a,b=b,a','a=1;b=2').timeit()
0.247945758469313663
模塊:profile和pstats提供了對更大代碼塊的測量工具
模塊:doctest
質量測試,測試代碼.
他將對函數文檔中的測試代碼進行測試,他使文檔的撰寫和軟件的測試融合了起來
例:
def average(values):
#注意>>> 和測試代碼之間要空一格,測試結果前面不要有空格
>>> print average([10,90,53])
51.0
- """ return sum(values,0.0)/len(values)
import doctest
doctest.testmod()
模塊:unittest
可以在一個獨立的文件中提供一個更全面的代碼測試.
例:
import unittest
class TestStatisticalFunctions(unittest.TestCase):
- def test_average(self):
- self.assertEqual(average([20,30,70]),40.0) self.assertEqual(round([1,5,7]),1)
self.assertRaises(ZeroDivisionError,average,[])
self.assertRaises(TypeError,average,20,30,70)
unittest.main()
其他一些常用模塊
xmlrpclib和SimpleXMLRPCServer可以在瑣碎的任務中調用遠程過程
email可以構建和解析復雜的消息結構,包括附件,文字編碼和頭協議等等
xml.dom和xml.sax
csv通用數據庫中直接讀寫
gettext,locale,codecs國際化(i18n)支持
模塊:pprint
美化打印(pretty printer)
例:
import pprint
t=[[ ['blue','cyan'] ,['green','red'],'yellow' ],'while']
>>> pprint.pprint(t,width=30)
[[['blue', 'cyan'],
- ['green', 'red'], 'yellow'],
模塊:textwrap
格式化段落來適應行寬
例:
import textwrap
doc="""Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you'll probably have to override _wrap_chunks()."""
>>> print textwrap.fill(doc,width=40)
Object for wrapping/filling text. The
public interface consists of the wrap()
and fill() methods; the other methods
are just there for subclasses to
override in order to tweak the default
behaviour. If you want to completely
replace the main wrapping algorithm,
you'll probably have to override
_wrap_chunks().
模塊:locale
國際化
例:
import locale
locale.setlocale(locale.LC_ALL,'English_United States.1252')
x=1234567.8
>>>locale.format("%d",x,grouping=True)
'1,234,567'
conv=locale.localeconv()
>>> locale.format("%s%.*f",(conv['currency_symbol'],conv['frac_digits'],x),grouping=True)
'$1,234,567.80'
模塊:string.template
生成句子的模版,輸入"張沈鵬",生成"大家好,我的名字是張沈鵬."
例:
from string import Template
t=Template('${village}flok send $$10 to $cause')
t.substitute(village='Nottingham',cause='the ditch fund')
'Nottinghamflok send $10 to the ditch fund'
當占位符沒有提供時substitute會拋出KeyError的異常
而safe_substitute可以在占位符提供不完整時保留占位符,而不拋出異常
模塊:struct
用于讀取二進制格式的文件
例:#H 代表unsigned short , read(2)因為unsigned short占2個bytes
#L 代表4字節的無符號整數
data=open('myfile.zip','rb').read()
start=0
for i in xrange(3):
- start+=14 fields=struct.unpack('LLLHH',data[start:start+16]) crc32,comp_size,uncompsize,filenamesize,extra_size=fields start+=16 filename=data[start:start+filenamesize] start+=filenamesize extra=data[start:start+extra_size] print filename,hex(crc32),comp_size,uncomp_size start+=extra_size+comp_size #下一個頭文件
模塊:threading
線程
例:
import threading,zipfile
class AsyncZip(threading.Thread)
background=AsyncZip('mydata.txt','myarchive.zip')
background.start()
print 'The main program continues to run in foreground'
background.join() #Wait for the background task finish
print 'Main program waitwd until background was done .'
模塊:logging
日志
例:
import logging
logging.debug('Debugging information')
logging.info('Information message')
logging.warning('Warning:coinfig file %s not found','server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
輸出:
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
模塊:wearef
不創建引用來跟蹤對象
例:
>>>import weakref,gc
>>>class A :
...def init (self,value):
... self.value=value
...def repr(self):
... return str(self.value)
...
>>>a=A(10) #create a reference
>>>d=weakref.WeakValueDictionary()
>>>d[’primary’]=a #does not create a reference
>>>d[’primary’] #fetch the object if it is still alive
10
>>>del a #remove the one reference
>>>gc.collect() #run garbage collection right away
0
>>>d[’primary’] #entry was automatically removed
Traceback(mostrecentcalllast):
File "<pyshell#108>",line1,in-toplevel-
d[’primary’] #entry was automatically removed
File "C:/PY24/lib/weakref.py" , line46 , in getitem
o = self.data[key]()
KeyError:’primary’
- 模塊:array 類似列表的對象,比默認的列表更緊湊,僅用來存儲數據 例: from array import array
#存儲雙字節無符號整數,編碼類型為H a=array('H',[4000,10,700,22222])
>>> sum(a)
26932
>>>a[1:3]
array('H',[10,700])
模塊:collections
提供了類似列表的deque對象,它從左邊添加(append)和彈出(pop)更快,但在內部查詢更慢.適用于隊列的實現和廣度優先樹的搜索
例:
from collection import deque
d=dequetask1","task2","task3
d.append("task4")
>>>print "Handling",d.popleft()
Handling task1
unsearched=deque([start_nodel])
def breadth_first_search(unsearched):
- node=unsearch.popleaf() for m in gen_moves(node):
- if is_goal(m):
unsearched.append(m)
模塊:bisect
操作存儲列表
例:
import bisect
scores=[(100,'perl'),(200,'tcl'),(400,'lua'),(500,'python')]
bisect.insort(scores,(300,'ruby'))
>>>scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
模塊:heapq
提供基于正常列表的堆實現,最小總是第一個元素(0點),對希望循環訪問最小元素但不想執行完整堆排列非常有用
例:
from heapq import heapify,heappop,heappush
data=[1,3,5,6,7,8,9,65,0]
heapify(data)
heappush(data,-5)
[heappop(data) for i in range(3) ]
>>> [heappop(data) for i in range(3) ]
[-5, 0, 1]
提供了一個Decimal數據類型,用于浮點數高精度的計算,高精度使Decimal可以執行二進制浮點數無法進行的模運算和等值測試
例:
from decimal import *
>>>Decimal('0.70')*Decimal('1.05'))
0.7350
>>> .70*1.05
0.73499999999999999
>>>sum([Decimal('0.1')*10==Decimal('1.0')])
True
>>>sum([0.1*10])==1.0
False
>>>Decimal('1.00')%Decimal('.10')
Decimal("0.00")
>>> 1.00%0.10
0.09999999999999995
getcontext().prec=36
>>>print Decimal(1)/Decimal(7)
0.142857142857142857142857142857142857