1. 從模塊導入函數的方法,也能夠爲函數提供別名:數據結構
import somemodule; from somemodule import somefunction1, somefunction2; from somemodule import *; from somemodule import somefunction as newfunctionname;ide
2. 序列解包支持多個賦值同時進行:函數
>>> x,y,z=1,2,3對象
>>> print x,y,z排序
1 2 3索引
>>> values=(3,2,1)ip
>>> x,y,z=values字符串
>>> print x,y,zstring
3 2 1it
3. 鏈式賦值:將同一個值賦給多個變量,注意同一性問題;x=y=somefuntion();
4. 增量賦值:x+=1; x*=2; str+='abc'; str*=2;
5. 布爾變量:False,None,0,"",(),[],{}都被看作假;其餘都被看作真;bool()函數將其餘值轉換爲布爾值;
6. 比較運算符:支持鏈式比較,如0<age<100;比較運算都支持字符串,按字母順序排列;
x==y; x<y; x>y; x>=y; x<=y; x!=y;
x is y; x is not y; #判斷x,y是否是同一對象;
x in y; x not in y; #判斷x是否是y的成員;
7. 布爾運算符:and; or; not
8. Python中的斷言使用關鍵字assert: assert 0<age<100
9. 循環while/for;遍歷一個集合時,用for:
>>> values=[3,2,1]
>>> for value in values: print value
...
3
2
1
>>> for value in range(1,3): print value
...
1
2
10. 遍歷字典元素:
>>> d={'x':1, 'y':2, 'z':3}
>>> for key in d: print key, 'corresponse to', d[key]
...
y corresponse to 2
x corresponse to 1
z corresponse to 3
>>> d={'x':1, 'y':2, 'z':3}
>>> for key,value in d.items(): print key, 'corresponse to', value
...
y corresponse to 2
x corresponse to 1
z corresponse to 3
11. 一些有用的迭代函數:
並行迭代:同時迭代兩個序列
>>> names=['ab','cd', 'ef']
>>> ages=[12,34,56]
>>> for i in range(len(names)): print names[i], 'is', ages[i], 'years old'
...
ab is 12 years old
cd is 34 years old
ef is 56 years old
>>> zip(names, ages)
[('ab', 12), ('cd', 34), ('ef', 56)]
>>> for name, age in zip(names, ages): print name, 'is', age, 'years old'
...
ab is 12 years old
cd is 34 years old
ef is 56 years old
編號迭代:取得迭代序列中對象的同時,獲取當前對象的索引
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index]='[censorted]'
翻轉和排序迭代:reversed()函數和sorted()函數,注意不是原地操做
>>> sorted([25, 3, 4, 8])
[3, 4, 8, 25]
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'
12. 循環中的else子句:
from math import sqrt
for n in range(99, 81, -1):
root=sqrt(n)
if root == int(root):
print n
break
else:
print "Didn't find it!"
13. 列表推導式
>>> [(x,y) for x in range(3) for y in range(3) if x+y>=3]
[(1, 2), (2, 1), (2, 2)]
14. pass語句什麼都不作,做爲佔位符使用;del語句用來刪除變量或者數據結構中的一部分,不能刪除值;exec語句執行字符串中的語句,可使用命名空間;eval語句對字符串中的表達式進行計算並返回結果;