itertools

作者: 噜噜迅儿 | 来源:发表于2018-06-15 14:22 被阅读0次

    counter()

    >>> import itertools
    >>> natuals = itertools.count(1)
    >>> for n in natuals:
    ...     print(n)
    ...
    1
    2
    3
    ...
    

    cycle()

    >>> import itertools
    >>> cs = itertools.cycle('ABC') # 注意字符串也是序列的一种
    >>> for c in cs:
    ...     print(c)
    ...
    'A'
    'B'
    'C'
    'A'
    'B'
    'C'
    ...
    

    repeat()

    >>> ns = itertools.repeat('A', 3)
    >>> for n in ns:
    ...     print(n)
    ...
    A
    A
    A
    

    takewhile()

    >>> natuals = itertools.count(1)
    >>> ns = itertools.takewhile(lambda x: x <= 10, natuals)
    >>> list(ns)
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    

    chain()

    >>> for c in itertools.chain('ABC', 'XYZ'):
    ...     print(c)
    # 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'
    

    groupby()

    >>> for key, group in itertools.groupby('AAABBBCCAAA'):
    ...     print(key, list(group))
    ...
    A ['A', 'A', 'A']
    B ['B', 'B', 'B']
    C ['C', 'C']
    A ['A', 'A', 'A']
    
    >>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
    ...     print(key, list(group))
    ...
    A ['A', 'a', 'a']
    B ['B', 'B', 'b']
    C ['c', 'C']
    A ['A', 'A', 'a']
    

    小结

    itertools模块提供的全部是处理迭代功能的函数,它们的返回值不是list,而是Iterator,只有用for循环迭代的时候才真正计算。

    相关文章

      网友评论

          本文标题:itertools

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