Merge list items based on condition within the list

前端 未结 4 1703
离开以前
离开以前 2021-01-03 11:38

I have a list of items : eg:

a = [\'IP 123 84\', \'apple\', \'mercury\', \'IP 543 65\', \'killer\', \'parser\', \'goat\',
     \'IP 549 54 pineapple\', \'dja         


        
4条回答
  •  梦毁少年i
    2021-01-03 12:06

    Kind of a fun way to do it:

    import itertools
    
    def predicate_grouper(li, predicate='IP'):
        indices = [i for i,x in enumerate(li) if x.startswith(predicate)]
        slices = [slice(*x) for x in itertools.zip_longest(indices,indices[1:])]
        for sli in slices:
            yield ' '.join(li[sli])
    

    demo:

    list(predicate_grouper(a))
    Out[61]: 
    ['IP 123 84 apple mercury',
     'IP 543 65 killer parser goat',
     'IP 549 54 pineapple django python']
    

提交回复
热议问题