Python split for lists

前端 未结 6 1307
眼角桃花
眼角桃花 2020-11-28 12:43

If we have a list of strings in python and want to create sublists based on some special string how should we do?

For instance

6条回答
  •  执笔经年
    2020-11-28 13:08

    One possible implementation using itertools

    >>> l
    ['data', 'more data', '', 'data 2', 'more data 2', 'danger', '', 'date3', 'lll']
    >>> it_l = iter(l)
    >>> from itertools import takewhile, dropwhile
    >>> [[e] + list(takewhile(lambda e: e != "", it_l)) for e in it_l if e != ""]
    [['data', 'more data'], ['data 2', 'more data 2', 'danger'], ['date3', 'lll']]
    

    Note*

    This is as fast as using groupby

    >>> stmt_dsm = """
    [list(group) for k, group in groupby(l, lambda x: x == "") if not k]
    """
    >>> stmt_ab = """
    it_l = iter(l)
    [[e] + list(takewhile(lambda e: e != "", it_l)) for e in it_l if e != ""]
    """
    >>> t_ab = timeit.Timer(stmt = stmt_ab, setup = "from __main__ import l, dropwhile, takewhile")
    >>> t_dsm = timeit.Timer(stmt = stmt_dsm, setup = "from __main__ import l, groupby")
    >>> t_ab.timeit(100000)
    1.6863486541265047
    >>> t_dsm.timeit(100000)
    1.5298066765462863
    >>> t_ab.timeit(100000)
    1.735611326163962
    >>> 
    

提交回复
热议问题