>>> str = "for i in range(0,10): print(i)">>> c = compile(str,‘‘,‘exec‘)>>> exec(c)0123456789>>> str2 = "3*3 + 4*4">>> c2 = compile(str2, ‘‘, ‘eval‘)>>> eval(c2)25
>>> exec(‘if True: print(100)‘)100>>> exec(‘‘‘x = 200if x > 100:print(x + 200)‘‘‘)400
>>> x = 1>>> print eval(‘x+1‘)2
>>> divmod(10,3)(3, 1)>>>
>>> li = [11,11,33,11,44,44,55]>>> max(li, key=li.count)11
>>> round(2.345)2>>> round(2.345,2)2.35
>>> isinstance(li,list)True>>>
def foo(arg, a):x = 1y = ‘xxxxxx‘for i in range(10):j = 1k = iprint locals()#调用函数的打印结果foo(1,2)#{‘a‘: 2, ‘i‘: 9, ‘k‘: 9, ‘j‘终端: 1, ‘arg‘: 1, ‘y‘: ‘xxxxxx‘, ‘x‘: 1}
>>> def func(x):x = x + xreturn x>>> list(map(func,li))[2, 4, 6, 8, 10]>>>
>>> li[1, 2, 3, 4, 5]>>> list(filter(lambda x: x> 3, li))[4, 5]
>>> list(range(10))[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> list(range(10,1,-2))[10, 8, 6, 4, 2]
>>> l1 = [1,2,3,4,5]>>> l2 = [‘a‘,‘b‘,‘c‘,‘d‘]>>> zip(l1, l2)<zip object at 0x0000000003419948>>>> list(zip(l1, l2))[(1, ‘a‘), (2, ‘b‘), (3, ‘c‘), (4, ‘d‘)]
#### 第一波 ####def foo():print ‘foo‘foo #表示是函数foo() #表示执行foo函数#### 第二波 ####def foo():print ‘foo‘foo = lambda x: x + 1foo() # 执行下面的lambda表达式,而不再是原来的foo函数,因为函数 foo 被重新定义了
>>> def outer():print("outer called.")>>> outer()outer called.
>>> def outer(func):print("before outer called.")func()print(" after outer called.")return func>>> def f1():print(" f1 called.")>>> f1 = outer(f1)before outer called.f1 called.after outer called.
>>> def outer(func):print("before outer called.")func()print(" after outer called.")return func>>> def f1():print(" f1 called.")>>> @outerdef f1():print(‘f1 called‘)before outer called.f1 calledafter outer called.
>>> def outer(func):def inner():print("before func called.")func()print(" after func called.")# 不需要返回func,实际上应返回原函数的返回值return inner>>>>>> @outerdef f1():print(‘f1 called‘)>>> f1()before func called.f1 calledafter func called.
>>>def outer(func):def inner(a, b):print("before func called.")ret = func(a, b)print(" after func called. result: %s" % ret)return retreturn inner>>>@outerdef f1(a, b):print(" f1(%s,%s) called." % (a, b))return a + b>>>f1()before func called.f1(a,b) calledafter func called.
>>>def outer(func):def inner(*args, **kwargs):print("before func called.")ret = func(*args, **kwargs)print(" after func called. result: %s" % ret)return retreturn inner>>>@outerdef f1(a, b):print(" f1(%s,%s) called." % (a, b))return a + b>>>@outerdef f2(a, b, c):print(" f2(%s,%s,%s) called." % (a, b, c))return a + b + c>>>f1()before func called.f1(a,b) calledafter func called.>>>f2()before func called.f1(a,b,c) calledafter func called.
原文:http://www.cnblogs.com/9527chu/p/5557898.html