专栏名称: 编程派
Python程序员都在看的公众号,跟着编程派一起学习Python,看最新国外教程和资源!
目录
相关文章推荐
Python开发者  ·  震撼!美国卡脖子下,中国工程师拖 4 ... ·  2 天前  
Python爱好者社区  ·  又见车企远程锁车?车主无奈,网友怒喷“谁敢买” ·  3 天前  
Python爱好者社区  ·  这才是最适合新手的python教程,640页超详细 ·  3 天前  
Python开发者  ·  三大云厂同时瘫了?Cursor、ChatGP ... ·  3 天前  
51好读  ›  专栏  ›  编程派

高效的 itertools 模块

编程派  · 公众号  · Python  · 2017-02-21 11:35

正文

请到「今天看啥」查看全文


from itertools import chain

  • >>>

  • >>> string = chain . from_iterable ( 'ABCD' )

  • >>> string . next ()

  • 'A'

  • compress

    compress 的使用形式如下:

    1. compress(data, selectors)

    compress 可用于对数据进行筛选,当 selectors 的某个元素为 true 时,则保留 data 对应位置的元素,否则去除:

    1. >>> from itertools import compress

    2. >>>

    3. >>> list(compress('ABCDEF', [1, 1, 0, 1, 0, 1]))

    4. ['A', 'B', 'D', 'F']

    5. >>> list(compress('ABCDEF', [1, 1, 0, 1]))

    6. ['A', 'B', 'D']

    7. >>> list(compress('ABCDEF', [True, False, True]))

    8. ['A', 'C']

    dropwhile

    dropwhile 的使用形式如下:

    1. dropwhile(predicate, iterable)

    其中, predicate 是函数, iterable 是可迭代对象。对于 iterable 中的元素,如果 predicate(item)为 true ,则丢弃该元素,否则返回该项及所有后续项。

    1. >>> from itertools import dropwhile

    2. >>>

    3. >>> list(dropwhile(lambda x: x 5, [1, 3, 6, 2, 1]))

    4. [6, 2, 1]

    5. >>>

    6. >>> list(dropwhile(lambda x: x > 3, [2, 1, 6, 5, 4]))

    7. [2, 1, 6, 5, 4]

    groupby

    groupby 用于对序列进行分组,它的使用形式如下:

    1. groupby(iterable[, keyfunc])

    其中, iterable 是一个可迭代对象, keyfunc 是分组函数,用于对 iterable 的连续项进行分组,如果不指定,则默认对 iterable 中的连续相同项进行分组,返回一个 ( key , sub - iterator ) 的迭代器。

    1. >>> from itertools import groupby

    2. >>>

    3. >>> for key, value_iter in groupby('aaabbbaaccd'):

    4. ... print key, ':', list(value_iter)

    5. ...

    6. a:

    7.    ['a', 'a', 'a']

    8. b:

    9.    ['b', 'b', 'b']

    10. a:

    11.    ['a', 'a']

    12. c:

    13.    ['c', 'c']

    14. d:

    15.    ['d']

    16. >>>

    17. >>> data = ['a', 'bb', 'ccc', 'dd', 'eee', 'f']

    18. >>> for key, value_iter in groupby(data, len):    # 使用 len 函数作为分组函数

    19. ... print key, ':', list(value_iter)

    20. ...

    21. 1:

    22.    ['a']

    23. 2:

    24.    ['bb']

    25. 3:

    26.    ['ccc']

    27. 2:

    28.    ['dd']

    29. 3:

    30.    ['eee']

    31. 1:

    32.    ['f']

    33. >>>

    34. >>> data = ['a', 'bb', 'cc', 'ddd', 'eee', 'f']

    35. >>> for key, value_iter in groupby(data, len):

    36. ... print key, ':', list(value_iter)

    37. ...







    请到「今天看啥」查看全文