Editor程序员

Python基础学习4:高级特性

2017-10-02  本文已影响44人  Andy_Ron

切片 (list, tuple, 字符串)

迭代(for in)

        from collections import Iterable

        isinstance('abc', Iterable) # str是否可迭代
        isinstance(123, Iterable) # 整数是否可迭代 

列表生成式(List Comprehensions)

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
L1 = ['Hello', 'World', 18, 'Apple', None]
[s.lower() for s in L2 if isinstance(s, str)]

生成器Generator(保存的是算法)

g = (x*x for x in range(10))
for n in g:
    print n 

函数:

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
    return 'done'

generator:

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'
def odd():
    print('step 1')
    yield 1
    print('step 2')
    yield(3)
    print('step 3')
    yield(5)
>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

参考:《Python教程》

上一篇 下一篇

猜你喜欢

热点阅读