美文网首页
高级特性-廖雪峰Python教程

高级特性-廖雪峰Python教程

作者: holykitty | 来源:发表于2019-03-23 01:27 被阅读0次

    切片

    L[0:3:x]表示,从索引0开始取,直到索引3为止,但不包括索引3x为步长。

    tuple也是一种list,唯一区别是tuple不可变。
    字符串'xxx'也可以看成是一种list,每个元素就是一个字符。

    >>> (0, 1, 2, 3, 4, 5)[:3]
    (0, 1, 2)
    >>> 'ABCDEFG'[:3]
    'ABC'
    >>> 'ABCDEFG'[::2]
    'ACEG'
    

    迭代

    isinstance
    可方法是通过collections模块的Iterable类型判断对象是否可迭代:

    >>> from collections import Iterable
    >>> isinstance('abc', Iterable) # str是否可迭代
    True
    >>> isinstance([1,2,3], Iterable) # list是否可迭代
    True
    >>> isinstance(123, Iterable) # 整数是否可迭代
    False
    

    enumerate
    Python内置的enumerate函数可以把一个list变成索引-元素对:

    >>> for i, value in enumerate(['A', 'B', 'C']):
    ...     print(i, value)
    ...
    0 A
    1 B
    2 C
    

    列表生成式

    >>> [x * x for x in range(1, 11)]
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    >>> [x * x for x in range(1, 11) if x % 2 == 0] # 加判断筛选
    [4, 16, 36, 64, 100]
    >>> [m + n for m in 'ABC' for n in 'XYZ'] # 使用两层循环,可以生成全排列
    ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
    

    参考:https://blog.csdn.net/renduy/article/details/42489471

    生成器

    如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator
    generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

    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
    

    for循环调用generator时,发现拿不到generatorreturn语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIterationvalue中:

    def fib(max):
        n, a, b = 0, 0, 1
        while n < max:
            yield b
            a, b = b, a + b
            n = n + 1
        return 'done'
    --------------------------------------------------------------------------
    >>> g = fib(6)
    >>> while True:
    ...     try:
    ...         x = next(g)
    ...         print('g:', x)
    ...     except StopIteration as e:
    ...         print('Generator return value:', e.value)
    ...         break
    ...
    g: 1
    g: 1
    g: 2
    g: 3
    g: 5
    g: 8
    Generator return value: done
    

    迭代器

    生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator
    list、dict、strIterable变成Iterator可以使用iter()函数:

    >>> isinstance(iter([]), Iterator)
    True
    >>> isinstance(iter('abc'), Iterator)
    True
    

    相关文章

      网友评论

          本文标题:高级特性-廖雪峰Python教程

          本文链接:https://www.haomeiwen.com/subject/ossapqtx.html