python 经典函数
lambda函数和and - or技巧的使用
当collapse为true时,返回" ".join(s.split()),而当collapse为false时,则返回s
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
这个函数主要着重于简单的模糊处理和默认参数处理
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusenik user') print complaint
a,b = b,a+b
>>> def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" ... a, b = 0, 1 ... while a < n: ... print a, ... a, b = b, a+b ... >>> # Now call the function we just defined: ... fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
函数接受和处理无法预计的参数
def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I'm sorry, we're all out of", kind for arg in arguments: print arg print "-" * 40 keys = sorted(keywords.keys()) for kw in keys: print kw, ":", keywords[kw] cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper='Michael Palin', client="John Cleese", sketch="Cheese Shop Sketch") ''' -- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- client : John Cleese shopkeeper : Michael Palin sketch : Cheese Shop Sketch '''
高级构建列表技巧
>>>alist = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] >>>alist [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9]
矩阵转置
>>> m = [ ... [1,2,3], ... [4,5,6], ... [7,8,9] ... ] >>> n = [[row[i] for row in m] for i in range(3)] >>> for nn in n: ... print nn ... [1, 4, 7] [2, 5, 8] [3, 6, 9] >>>
格式化输出
for x in range(1,10): #right str1 = '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) #right str2 = str.rjust(repr(x),2)+str.rjust(repr(x*x),3)+str.rjust(repr(x*x*x),4) #left str3 = str.ljust(repr(x),2)+str.ljust(repr(x*x),3)+str.ljust(repr(x*x*x),4) #center str4 = str.center(repr(x),2)+str.center(repr(x*x),3)+str.center(repr(x*x*x),5) ol = "| %s | %s | %s | %s |" % (str1,str2,str3,str4) print ol
运行结果
文件操作应当使用with语句,保证能及时释放文件对象
with open("myfile.txt") as f: for line in f: print line,