Merge list items based on condition within the list

前端 未结 4 1686
离开以前
离开以前 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条回答
  •  攒了一身酷
    2021-01-03 12:29

    Using a generator.

    def merge(x, key='IP'):
        tmp = []
        for i in x:
            if (i[0:len(key)] == key) and len(tmp):
                yield ' '.join(tmp)
                tmp = []
            tmp.append(i)
        if len(tmp):
            yield ' '.join(tmp)
    
    a = ['IP 123 84','apple','mercury','IP 543 65','killer','parser','goat','IP 549 54 pineapple','django','python']
    print list(merge(a))
    
    ['IP 123 84 apple mercury', 'IP 543 65 killer parser goat', 'IP 549 54 pineapple django python']
    

提交回复
热议问题