注:这里忽略了生成器,装饰器,交换变量等熟知技巧
1. 函数参数unpack
老生常谈的了:
def foo(x, y): print x, y alist = [1, 2]adict = {'x': 1, 'y': 2} foo(*alist) # 1, 2foo(**adict) # 1, 2
2. 链式比较操作符
>>> x = 3>>> 1 < x < 5True>>> 4 > x >=3True
3. 注意函数的默认参数
>>> def foo(x=[]):... x.append(1)... print x...>>> foo()[1]>>> foo()[1, 1]
更安全的做法:
>>> def foo(x=None):... if x is None:... x = []... x.append(1)... print x...>>> foo()[1]>>> foo()[1]>>>
4. 字典有个get()方法
dct.get(key[,default_value]), 当字典dct中找不到key时,get就会返回default_value
sum[value] = sum.get(value, 0) + 1
5. 带关键字的格式化
>>> print "Hello %(name)s !" % {'name': 'James'}Hello James !>>> print "I am years %(age)i years old" % {'age': 18}I am years 18 years old
更新些的格式化:
>>> print "Hello {name} !".format(name="James")Hello James !
快有些模板引擎的味道了:)
6. for…else 语法
>>> for i in (1, 3, 5):... if i % 2 == 0:... break... else:... print "var i is always an odd"...var i is always an odd>>>
else语句块会在循环结束后执行,除非在循环块中执行break
7. dict 的特殊方法__missing__
Python 2.5之后引入的。当查找不到key的时候,会执行这个方法。
>>> class Dict(dict):... def __missing__(self, key):... self[key] = []... return self[key]...>>> dct = Dict()>>> dct["foo"].append(1)>>> dct["foo"].append(2)>>> dct["foo"][1, 2]
这很像collections.defaultdict不是吗?
>>> from collections import defaultdict>>> dct = defaultdict(list)>>> dct["foo"][]>>> dct["bar"].append("Hello")>>> dctdefaultdict(<type 'list'>, {'foo': [], 'bar': ['Hello']})
8. 切片操作的步长参数
还能用步长-1来反转链表:
9.另一种字符串连接
>>> Name = "Wang" "Hong">>> Name'WangHong'
连接多行:
>>> Name = "Wang" /... "Hong">>> Name'WangHong'10. Python解释器中的”_” >>> range(4)[0, 1, 2, 3]>>> _[0, 1, 2, 3]
新闻热点
疑难解答