1.1. Óï·¨
1.1.1. if
x=int(raw_input("Please enter an integer:"))
if x<0:
print 'Negative Number'
elif x==0:
print 'Zero'
else:
print 'Positive Number'
1.1.2. for
a=['cat','door','example']
for x in a:
print x
#Èç¹ûÒªÐÞ¸ÄaµÄÄÚÈÝ£¬ÔòÓÃaµÄ¸±±¾Ñ»·£¬È磺
for x in a[:] :
.....................
>>>range(10,0,-3)
[10,7,4,1]
a=['cat','door','example']
for i in range(len(a)):
print i,a[i]
break,continue Ó÷¨ºÍC£«£«ÖÐÀàËÆ
1.1.3. pass
while True:
pass #ºöÂÔ£¬Ê²Ã´Ò²²»×ö
def fib(n=1000):#²ÎÊý¿ÉÒÔÓÐĬÈÏÖµ£¬¶à¸ö¿ÉÑ¡²ÎÊý¸³Öµ¿ÉÒÔÖ±½Óд"²ÎÊý±äÁ¿Ãû£½Öµ"À´¿ìËÙ¸³Öµ
"""ÕâÀï¸øº¯ÊýдÎĵµ×¢ÊÍ"""
a,b=0,1
while b<n:
print b
a,b=b,a+b
#º¯Êý¿ÉÒÔÖØÃüÃû,Èç
f=fib
f(223)
1.1.4. in
if 'yes' in ('y','ye','yes'):print 'ok'
1.1.5. ²ÎÊý¸ñʽ **para
#²ÎÊý¸ñʽΪ **para ±íʾ½ÓÊÜÒ»¸ö×Öµä,Ϊ *para ±íʾ½ÓÊÜÒ»¸öÔª×é
def test(para1,*args,**dic):
print para1
for arg in args : print arg
keys=dic.keys()
keys.sort()
for key in keys:print key ,':',dic[key]
1.1.6. Lambdaº¯Êý
def make_incrementor(n):
return lambda x: x+n
f=make_incrementor(n)
>>>f(0)
42
>>>f(1)
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
a=[1,2,3,4,5,6]
del a[0]
>>>a
[2,3,4,5,6]
del a[2:4]
>>>a
[2,3,6]
del a[:]
>>>a
[]
del a
>>>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£¨¼¯ºÏ£©£ºÎÞÐò²»Öظ´µÄÔªËØ¼¯
basket = ['apple','orange','apple','pear','apple','banana']
fruit=set(basket)
>>>fruit
set(['orange', 'pear', 'apple', 'banana'])
>>>'orange' in fruit
True
a=set('abracadabew')
>>>a
set(['a', 'c', 'b', 'e', 'd', 'r', 'w'])
b=set('wajgwaoihwb')
>>> b
set(['a', 'b', 'g', 'i', 'h', 'j', 'o', 'w'])
>>> a-b #²î
set(['c', 'r', 'e', 'd'])
>>> a|b #²¢
set(['a', 'c', 'b', 'e', 'd', 'g', 'i', 'h', 'j', 'o', 'r', 'w'])
>>> a&b #½»
set(['a', 'b', 'w'])
>>>a^b #(²¢-½»)
set(['c', 'e', 'd', 'g', 'i', 'h', 'j', 'o', 'r'])
1.1.12. dict
×Öµä:¹Ø¼ü×ÖΪ²»¿É±äÀàÐÍ,Èç×Ö·û´®,ÕûÊý,Ö»°üº¬²»¿É±ä¶ÔÏóµÄÔª×é.ÁбíµÈ²»¿ÉÒÔ×÷Ϊ¹Ø¼ü×Ö.Èç¹ûÁбíÖдæÔڹؼü×Ö¶Ô,¿ÉÒÔÓÃdict()Ö±½Ó¹¹Ôì×Öµä.¶øÕâÑùµÄÁбí¶Ôͨ³£ÊÇÓÉÁбíÍÆµ¼Ê½Éú³ÉµÄ.
tel={'jack':4098,'sape':4139}
tel['guido']=4127
>>> tel
{'sape': 4139, 'jack': 4098, 'guido': 4127}
>>>tel['jack']
4098
del tel['sape']
>>>tel.keys()
['jack', 'guido']
>>>tel.has_key('jack')
True
knight={'gallahad':'the pure','robin':'the brave'}
for k,v in knight.iteritems():
print k,v
Êä³ö:
gallahad the pure
robin the brave
enumerate()·µ»ØË÷ÒýλÖúͶÔÓ¦µÄÖµ
for i,v in enumerate(['tic','tac','toe'])
print i,v
Êä³ö: 0 tic
1 tac
2 toe
1.1.13. None
±íʾ¸ÃÖµ²»´æÔÚ
1.1.14. zip
zipÓÃÓÚ¶à¸ösequenceµÄÑ»·
questions=['name','quest','favorite color']
answers=['lancelot','the holy grail','blue']
for q,a in zip(questions,answers):
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.15. reversed·´ÏòÑ»·
for i in reversed(range(1,4)):
print i
Êä³ö:
3
2
1
1.1.16. sortedÅÅÐò
1.1.17. sequence±È´óС
list<string<tuple(ÒòΪ×Öĸ±íÖÐlÔÚsǰ...)
ͬÀà±È´óС°´ÕÕ×ÖµäÐò
1.1.18. µ¼ÈëÄ£¿é
Ä£¿éµÄ²éÕÒ·¾¶
1.µ±Ç°µÄĿ¼
2.»·¾³±äÁ¿PYTHONPATHËùÖ¸µÄĿ¼Áбí
3.python½âÊÍÆ÷µÄ°²×°Ä¿Â¼
È罫´úÂë±£´æÉÏÊöµÄÒ»¸öĿ¼ÖеĵÄfibo.pyÎļþÖÐ,±ã¿ÉÒÔ
import fibo
fibo.function().............
Èç¹ûÏëÖ±½ÓʹÓÃfibo.function¿ÉÒÔÖØÃüÃûÕâ¸öº¯Êý,Èç
f=fibo.function
f()
Ò²¿ÉÒÔ
form fibo import function
function()
ÉõÖÁ¿ÉÒÔform fibo import *
¿ÉÒÔ form °ü.×Ó°ü.Ä£¿é imort º¯Êý
È»ºó¾ÍÖ±½ÓʹÓøú¯Êý,²»ÐèÒª¼Óǰ׺
1.1.19. °ü
ÒýÓÃÍÆ¼öд·¨Îª
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"]
°üµÄ×÷ÕßÔÚ·¢²¼°üʱ¿ÉÒÔ¸üÐÂÕâ¸öÁбí,Ò²¿ÉÒÔ¸ù¾ÝÐèÒªÈÃij¸öÄ£¿é²»Ö§³Öimport *
¶ÔÓÚ°üÖÐͬһ¸öÎļþ¼ÐϵÄÄ£¿é¿ÉÒÔ°Ñ
form °ü.×Ó°ü imort Ä£¿é
¼òдΪ imort Ä£¿é
1.1.20. ¸ñʽ»¯Êä³ö
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.21. µÈЧ´úÂë
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.22. ¶ÁдÎļþ:
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: #½»»»Í¨µÀ
- print line
f.write("hello\n") #Èç¹ûҪдÈë×Ö·û´®ÒÔÍâµÄÊý¾Ý,ÏȽ«Ëûת»»Îª×Ö·û´®.
f.tell() ·µ»ØÒ»¸öÕûÊý,±íʾµ±Ç°ÎļþÖ¸ÕëµÄλÖÃ(¾ÍÊǵ½ÎļþÍ·µÄ±ÈÌØÊý).
f.seek(Æ«ÒÆÁ¿,[ÆðʼλÖÃ])
ÓÃÀ´Òƶ¯ÎļþÖ¸Õë
Æ«ÒÆÁ¿:µ¥Î»:±ÈÌØ,¿ÉÕý¿É¸º
ÆðʼλÖÃ:0-ÎļþÍ·,ĬÈÏÖµ;1-µ±Ç°Î»ÖÃ;2-Îļþβ
f.close() ¹Ø±ÕÎļþ
1.1.23. 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:
- #instÊǸÃÒì³£ÀàµÄÒ»¸öʵÀý print inst.args #´òÓ¡³ö²ÎÊýÃû
print inst #Ö±½Ó´òÓ¡strÊôÐÔ x,y=inst print 'x=',x print 'y=',y
Èç¹ûÅ׳öÒ쳣ûÓÐÖ¸¶¨²ÎÊý,Ôò²¶»ñÒ쳣ʱµÄ²ÎÊý°üº¬µÄÊǸÃÒì³£µÄĬÈÏÐÅÏ¢
>>>try:
- 1/0
except ZeroDivisionError,detail:
- print 'Handling run-time error:',detail
Handling run-time error:integer division or modulo by zero
×Ô¶¨ÒåÒì³£:¹ßÀýÊÇÒÔError½áβµÄÀ࣬ͬÀàµÄÒì³£Ò»°ãÅÉÉú×Ôͬһ¸ö»ùÀà,»ùÀàÒì³£¿ÉÒÔÆ¥ÅäÅÉÉúÀàÒì³£
class MyError(Exception):
def init(self,value):
- self.value=value
def str(self):
- return reper(self.value)
try:
raise MyError(2,2)
except MyError,e:
- print 'My exeception occurred,value',e.value
>>>
My exeception occurred,value 4
finally£ººÍC£«£«ÖÐÀàËÆ,¼´Ê¹ÊÇbreak£¬continue»òreturnºóÒ»Ñù»áÖ´ÐС£Ò»°ãÓÃÓÚÊÍ·Å×ÊÔ´£¬ÈçÎļþ£¬ÍøÂçÁ¬½Ó¡£
def divide(x,y):
- try:
- try:
- result=x/y
except ZeroDivisionError:
- print "zero"
- print 'result=',result
- print 'finish'
- try:
with #with¿ÉÒÔ°ïÖúÄã×Ô¶¯ÊÍ·Å×ÊÔ´,ÏÂÒ»¸ö°æ±¾¿ÉÓÃ
with open('myfile.txt') as f:
- for line in f:
- print line
#¸ÃÎļþ»á×Ô¶¯±»ÊÍ·Å
1.1.24. ³õʶÀà
class ClassName:
"ÀàÎĵµ,¿ÉÒÔͨ¹ýÀàÃû.doc·ÃÎÊ" #ÀàµÄ˽ÓбäÁ¿ÊÇÖÁÉÙÒÔ˫ϻ®Ïß¿ªÍ·,×î¶àÒÔµ¥Ï»®Ïß½áβµÄÀà±äÁ¿,µ÷ÓÃʱ»á±äÁ¿Ãû»á±»»ìÏý³É _ClassName±äÁ¿Ãû i=12345 def f(self)
- return "hello world"
def init(self):
- "¹¹Ô캯Êý,¿ÉÒÔ³õʼ»¯±äÁ¿,¿ÉÒÔÓвÎÊý" #¿ÉÒÔͨ¹ýselfµ÷Óõ±Ç°ÀàµÄº¯ÊýºÍÊý¾Ý self.data=[]
#´´½¨ÀàʵÀý
x=ClassName()
#¸øÀàµÄ·½·¨ÖØÃüÃû
xf=ClassName.f
1.1.24.1. Àà¼Ì³Ð
class DerivedClassName(BassClassName):
- ...................................
Èç¹û»ùÀඨÒåÔÚÁíÒ»¸öÄ£¿éÖÐ, Ҫд³É
modname.BaseClassName
ÅÉÉúÀàµÄº¯Êý»á¸²¸Ç»ùÀàµÄͬÃûº¯Êý,Èç¹ûÏëÀ©³ä¶ø²»ÊǸÄд»ùÀàµÄº¯Êý,¿ÉÒÔÕâÑùµ÷ÓûùÀຯÊý
BaseClassName.methodname(self,arguments)
×¢Òâ:¸Ã»ùÀàÒªÔÚµ±Ç°È«¾ÖÓò»ò±»µ¼Èë
1.1.24.2. ¶àÖØ¼Ì³Ð
Àà¶à¼Ì³Ð//СÐÄʹÓÃ
class DerivedClassName(Base1,Base2,Base3):
.................
¶ÔÓÚÒ»¸öº¯ÊýµÄ½âÎö¹æÔòÊÇÉî¶ÈÓÅÏÈ,ÏÈÊÇBase1,È»ºóÊÇBase1µÄ»ùÀà,ÖîÈç´ËÀà.
1.1.25. Iterators µü´úÆ÷
for element in [1,2,3]:
- print element
for key in {'one':1,'two':2}:
- print key
for line in open("my.txt"):
- print line
ÔÚÈÝÆ÷Öж¨Òånext()ÖðÒ»·µ»ØÔªËØ,²¢ÔÚµü´úÍê³ÉʱÅ׳öStopIterationÒì³£,È»ºó¶¨Òåiter()·µ»Øself,±ã¿ÉÒÔfor...inÑ»·
ÓÃGenerators(Éú³ÉÆ÷)¿ÉÒÔ¿ìËÙÉú³ÉÒ»¸öÐòÁÐ,ÔÚµ÷ÓÃnext()ʱÒÀ´Î·µ»ØÐòÁÐÖеÄÖµ.
def reverse(data):
- for index in range(len(data)-1,-1,-1):
- yield data[index]
#yield»á×Ô¶¯´´½¨next()ºÍiter(),ÿ´Îµ÷ÓÃnext()ʱyield»á½øÐÐÏÂÒ»²½Ñ»·,²¢ÔÚyield´¦·µ»ØÖµ
1.1.26. Éú³ÉÆ÷±í´ïʽ
Éú³ÉÆ÷±í´ïʽ:ÀàËÆÓÚûÓÐÖÐÀ¨ºÅµÄÁбíÍÆµ¼Ê½,¿ÉÓÃÔÚ²ÎÊýÖÐ
>>>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))
- 260
>>>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\')
- print line
Ä£¿é: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"
- t=zlib.compress(s)
>>>len(s)
23
>>>len(t)
16
>>>zlib.decompress(t)
"which which which which"
>>>zilb.crc(32)
-487390043
Ä£¿é:timeit
ÐÔÄܲâÊÔ
Àý:
from timeit import Timer
#TimerµÄµÚÒ»¸ö²ÎÊýÊÇÒª²âÊÔʱ¼äµÄÓï¾ä,µÚ¶þ¸ö²ÎÊýÊdzõʼ»¯
#timeitµÄ²ÎÊýÊDzâÊÔÓï¾äµÄÖ´ÐдÎÊý,ĬÈÏÖ´ÐÐ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
ÖÊÁ¿²âÊÔ,²âÊÔ´úÂë.
Ëû½«¶Ôº¯ÊýÎĵµÖеIJâÊÔ´úÂë½øÐвâÊÔ,ËûʹÎĵµµÄ׫дºÍÈí¼þµÄ²âÊÔÈÚºÏÁËÆðÀ´
Àý:
def average(values):
- """Computer average
#×¢Òâ>>> ºÍ²âÊÔ´úÂëÖ®¼äÒª¿ÕÒ»¸ñ,²âÊÔ½á¹ûÇ°Ãæ²»ÒªÓпոñ
>>> 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)
- self.assertEqual(average([20,30,70]),40.0) self.assertEqual(round([1,5,7]),1)
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'],
- 'while']
Ä£¿é: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)
def init(self , infile , outfile):
- self.infile=infile self.outfile=outfile
f=zipfile.ZipFile(self.outfile , 'w' , zipfile.DEFLATED) f.write(self.infile) f.close() print 'Finished background zip of: ', self.infile
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 .'
- Ä£¿é:Queue жàÏ̵߳Ä×ÊÔ´µ÷ÓÃ
Ä£¿é: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):
- return m
- if is_goal(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µã),¶ÔÏ£ÍûÑ»··ÃÎÊ×îÐ¡ÔªËØµ«²»ÏëÖ´ÐÐÍêÕû¶ÑÅÅÁзdz£ÓÐÓÃ
Àý:
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Êý¾ÝÀàÐÍ,ÓÃÓÚ¸¡µãÊý¸ß¾«¶ÈµÄ¼ÆËã,¸ß¾«¶Èʹ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

