使用Python来编写也有很长一段时间了,也想着如何优化本身的代码,随之也搜了一些问题。
其中印象比较深入的就是stackoverflow上的一个问题解答了。python
Argument Unpackingexpress
可使用 * 和 ** 分别将一个列表和一个字典解包为函数参数如:app
def draw_point(x, y): # do something tuple = (6, 8) dir = {'x': 6, 'y': 8} draw_point(*tuple) draw_point(**dir)
Decorators 函数
装饰器的做用就是在不须要修改原函数代码的前提下增长新的功能,在调用原函数的时候先执行装饰器,如:优化
def print_before_func(func): def wrapper(*args, **kwargs): print("print before func") return func(*args, **kwargs) return wrapper @print_befor_func def write(text): print(text) write(Hello world) 结果: print before func Hello world
Dictionary default .get value this
字典中有一个get()
方法。若是你使用dict['key']
的方式而key
不存在的话就会出现异常。使用dict.get('key')
的话若是key
不存在则只会返回None
。固然get()
方法提供了第二个参数,若是返回None
则会返回第二个参数的值。code
num = dict.get('num', 0)
Enumeration
使用enumeration包住一个可迭代对象,它会将index和item绑在一块儿,返回一个enumeration对象,如:orm
a = ['a', 'b', 'c', 'd'] for index, item in enumeration(a): print(index, item) ··· 0 a 1 b 2 c 3 d ···
在同时须要索引和值的时候颇有用对象
For/else
语法以下:blog
for i in foo: if i == 0: break else: print("it was never 0")
else
代码块会在循环正常结束后执行,也就是说没用出现break
时才会调用else
代码块,上面代码等价于:
found = False for i in foo: if i == 0: found = True break if not found: print("it was never 0")
这个语法挺容易让人混淆的,全部在使用的时候最好是注释一下,以避免被其余小伙伴搞错含义了。
上面的代码也等价于:
if any(i == 0 for i in foo): pass else: print("it was never 0")
Generator expressions
假如你这样写:
x = (n for n in foo if bar(n))
你将会获得一个生成器,并能够把它付给一个变量x。如今你能够像下面同样使用生成器:
for n in x: print(n)
这样作的好处就是节省内存了。你不须要中间存储,而若是像下面这样的话,则须要:
x = [n for n in foo if bar(n)] # 列表推导
在某些状况下,这会致使极重要的速度提高。
你能够添加许多if语句到生成器的尾端,基本复制for循环嵌套:
>>> n = ((a,b) for a in range(0,2) for b in range(4,6)) >>> for i in n: ... print i (0, 4) (0, 5) (1, 4) (1, 5)
使用生成器最大的好处就是节省内存了。由于每个值只有在你须要的时候才会生成,而不像列表推导那样一次性生成全部的结果。
List stepping
切片操做符中的步长(step)参数。例如:
a = [1,2,3,4,5] >>> a[::2] # iterate over the whole list in 2-increments [1,3,5]
特殊例子x[::-1]
对‘x反转’来讲至关有用。
>>> a[::-1] [5,4,3,2,1]
固然,你可使用reversed()
函数来实现反转。
区别在于,reversed()返回一个迭代器,因此还须要一个额外的步骤来将结果转换成须要的对象类型。
这个特性在判断例如回文的时候灰常有用,一句话搞定
True if someseq == someseq[::-1] else False
Named string formatting
%-格式化接收一个字典(也适用于%i%s等)
>>> print "The %(foo)s is %(bar)i." % {'foo': 'answer', 'bar':42} The answer is 42.
try/except/else
else语句块只有当try语句正常执行(也就是说,except语句未执行)的时候,才会执行。
finally则不管是否异常都会执行。
try: Normal execution block except A: Exception A handle except B: Exception B handle except: Other exception handle else: if no exception,get here finally: this block will be excuted no matter how it goes above