Python那些相见恨晚的语法

1.列表推导式

>>> {x: 10 * x for x in xrange(5)}
{0: 0, 1: 10, 2: 20, 3: 30, 4: 40}
>>> {10 * x for x in xrange(5) if x > 1}
set([40, 20, 30])

2.切片

>>> L = ['Michael', 'Sarah', 'Tracy']
>>> L[:3]
['Michael', 'Sarah', 'Tracy']
>>> L[1:3]
['Sarah', 'Tracy']
>>> L[-2:-1]
['Bob']

>>> L = list(range(100))
>>> L
[0, 1, 2, 3, ..., 99]
# 前10个数字,每2个取一个
>>> L[:10:2]
[0, 2, 4, 6, 8]
# 所有数,每5个取一个
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

3.生成器(斐波拉契数列)

# 著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
    return 'done'

#上面的队列转换为生成器,只需要把print(b)改为yield b即可
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'

4.递归(递归虽然运行效率比较低,但在对一些树形结构进行运算时,会非常方便)

# 计算阶乘 fact(n) = n! = 1 x 2 x 3 x ... x (n-1) x n = (n-1)! x n = fact(n-1) x n
def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)

# 递归的计算过程
===> fact(5)
===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120

5.lambda匿名函数

>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]

# lambda函数可代替下面函数定义
def f(x):
    return x * x

6.装饰器/闭包

# 一个能打印日志的decorator
def log(func):
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper

# 调用方式
@log
def now():
    print('2015-3-25')

7.zip函数

>>> l = [[1, 2, 3], [4, 5, 6]]
>>> zip(*l)
[(1, 4), (2, 5), (3, 6)]

alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']
for a, b in zip(alist, blist):
  print a, b

8.map/filter/reduce

>>> map(lambda x:x*2, xrange(0,10))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> filter(lambda x:x%2==0, xrange(0,10))
[0, 2, 4, 6, 8]
>>> reduce(lambda x,y:x+y, xrange(0,10))
45

9.enumerate

>>> a = ['a', 'b', 'c', 'd', 'e'] 
>>> for index, item in enumerate(a): 
        print index, item 
        ... 
0 a 
1 b
2 c 
3 d 
4 e

10.接连比较

if a < b < c:
    pass

11.数值调换

x, y = y, x

12.defaultdict

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
        d[k].append(v)

>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

你可能感兴趣的:(Python那些相见恨晚的语法)