Combine elements of lists if some condition

后端 未结 3 1785
一生所求
一生所求 2021-01-18 00:06

How do I combine the elements of a list if some condition is met.

I\'ve seen posts about combining elements of a list, but not with some condition.

3条回答
  •  自闭症患者
    2021-01-18 00:46

    Use itertools.groupby:

    >>> from itertools import groupby
    >>> out = []
    >>> for lst in words:
        d = []
        for k, g in groupby(lst, lambda x: '!' in x):
            if k:
                d.append(', '.join(g))
            else:
                d.extend(g)
        out.append(d)
    ...     
    >>> out
    [['this', 'that!', 'riff', 'raff'],
     ['hip', 'hop!, flip!', 'flop'],
     ['humpty', 'dumpty!, professor!, grumpy!']]
    

提交回复
热议问题