Merge list items based on condition within the list

前端 未结 4 1679
离开以前
离开以前 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:07

    import re    
    def group_IP_list(lst):
        groups = []
        word_group = []
        for list_item in lst:
            if re.search(r'^IP',list_item) and word_group:
                groups.append(' '.join(word_group)) 
            elif re.search(r'^IP',list_item):
                word_group = [list_item]
            else: 
                word_group.extend([list_item])
        groups.append(' '.join(word_group)) 
        return groups
    
    #Usage: 
    a = ['IP 123 84','apple','mercury','IP 543 65','killer','parser','goat','IP 549 54   pineapple','django','python']
    print group_IP_list(a)
    #Result:
    ['IP 123 84 apple mercury', 'IP 123 84 apple mercury killer parser goat', 'IP 123 84 apple mercury killer parser goat django python']
    

提交回复
热议问题