交換賦值
a,b = b,a
文件讀寫
使用with進(jìn)行文件操作避免忘記寫關(guān)閉文件導(dǎo)致的不良影響
with open('','r') as f:
do_sth(f)
格式化輸出 str.fomart
print('{A} hit {B}'.format(A='Tom',b='Jerry'))
三目運算 A?X:Y
X if A else Y
switch...case
用字典的get方法實現(xiàn)C語言中的switch...case語句
def f(n):
return{
0:'hei',
1:'oh'
}.get(n,'a number')
列表理解
編程的時候時常遇到下面這種情況
res = []
for s in t:
res.append(s[0])
用列表理解簡化上述代碼枚碗,方括號就表示構(gòu)建新的列表
[s[0] for s in t]
生成器
生成器表達(dá)式與列表理解相似
g = (x**2 for x in range(5))
sum(g)
表達(dá)式返回的結(jié)果是一個生成器對象把介,而不是一次把結(jié)果計算出來饰序,它通過next方法迭代得到下一個值,也可以用for遍歷所有值
for val in g:
print(val)
靈活使用集合
集合作為python的內(nèi)置數(shù)據(jù)類型,向其中添加元素俺驶,檢查成員都很快,它的一個重要特性是一個元素在一個集合中只出現(xiàn)一次硕噩,因此可以用集合來去重咱娶。
a - b # 集合減法
a <= b # a否是b的子集
更規(guī)范的注釋
行注釋
x # an integer
塊注釋
def fuction1(A,b):
''' Replace the value in A with b and save as a new list res
Args:
A: list, list to ...
b: int, a number that ...
Returns:
res: list, a new list
'''
文檔注釋
'''
--------------------------------
File Name: fun.py
Description: file to test
Author: zeng
Change Activity:
17.07.02 delete function1
--------------------------------
'''