你所需要的,不仅仅是一个好用的代理。
注:这里忽略了生成器,装饰器,交换变量等熟知技巧
老生常谈的了:
def foo(x, y):
print x, y
alist = [1, 2]
adict = {'x': 1, 'y': 2}
foo(*alist) # 1, 2
foo(**adict) # 1, 2
>>> x = 3
>>> 1 < x < 5
True
>>> 4 > x >=3
True
>>> 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]
>>>
dct.get(key[,default_value]), 当字典dct中找不到key时,get就会返回default_value
sum[value] = sum.get(value, 0) + 1
>>> 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 !
快有些模板引擎的味道了:)
>>> 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
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")
>>> dct
defaultdict(<type 'list'>, {'foo': [], 'bar': ['Hello']})
还能用步长-1来反转链表:
>>> a = [1, 2, 3, 4, 5]
>>> a[::2]
[1, 3, 5]
>>> a[::-1]
[5, 4, 3, 2, 1]
>>>
>>> Name = "Wang" "Hong"
>>> Name
'WangHong'
连接多行:
>>> Name = "Wang" \
... "Hong"
>>> Name
'WangHong'
>>> range(4)
[0, 1, 2, 3]
>>> _
[0, 1, 2, 3]
_即Python解释器上一次返回的值
Python描述器是Python 中很魔幻的东西,方法等都是描述器。不再举例
import this
>>> [(i, j) for i in range(3) for j in range(i)]
[(1, 0), (2, 0), (2, 1)]