1.計算階乘
通常你是這樣寫:
def func(n): return n<2 and 1 or n*func(n-1)
reduce (lambda x,y:x*y,range(1,n)) #簡單多了?高大上了?
2.寫(讀)文件:
f=open(name,'w')f.write(data)f.close()
也可以這樣:
with open(name,'w') as f: f.write(data) #不用關閉文件!
3.python 的私有:
想私有方法或者私有變量:方法或變量名前加'__': def __myfunc() __color = ''
"單下劃線" 開始的成員變量叫做保護變量,意思是只有類對象和子類對象自己能訪問到這些變量;
"雙下劃線" 開始的是私有成員,意思是只有類對象自己能訪問,連子類對象也不能訪問到這個數據。
4.遍歷目錄:
import os.pathdef Vist(arg,dirname,names): for filepath in names: PRint os.path.join(dirname,filepath) path ='xxxx' 目錄路徑os.path.walk(path,Vist,()) #Vist 回調函數 先遍歷頂級目錄,在遍歷目錄中文件
5.1,2,3,4,5的全排列
from itertools import permutations p = list(permutations('12345'))當然也可以用遞歸,或者好多好多個for
遞歸:
def perms(elements): if len(elements) <=1: yield elements else: for perm in perms(elements[1:]): for i in range(len(elements)): yield perm[:i] + elements[0:1] + perm[i:]for item in list(perms([1,2,3,4,5])): print item
6.獲取上一級目錄
import os,os.pathpath = os.getcwd()parent_path = os.path.dirname(path)print pathprint parent_path
7.combinations(iterable, r),創建一個迭代器,返回iterable中所有長度為r的子序列(不重復)
from itertools import *for i in combinations([1, 2,3,4], 2): print i
8.功能同上,重復
from itertools import *for i in combinations_with_replacement([1, 2, 3,4], 2): print i
9.刪除列表中相同的字典
from itertools import *l = [{'name':'zhang', 'age':18}, {'name':'zhang', 'age':18}, {'name':'li', 'age':18}]for d1, d2 in combinations(l, 2): a = list(set(d1.items())^set(d2.items())) if len(a) == 0: i = l.index(d1) l.pop(i)print l10.同時遍歷兩個數組(字典),[過去寫爬蟲(beautifulSoup)的時候遇到過,同時遍歷兩類元素的]
b = [1,2,3]a = [4,5,6,7]for i, j in zip(a, b): print i, j
11.當你有兩個列表,其中一個為空,如果想使用其中一個不空列表的時候
b = [1,2,3]a = []for i in set(a) | set(b): print i
12.直接插入到列表某位置:
a=[1,2,3]a.insert(3,1111)print a
新聞熱點
疑難解答