Merge list items based on condition within the list

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

    If string 'IP' only exists at the head of some elements of a, join the list and then split it:

    In [99]: ['IP'+i for i in ''.join(a).split('IP')[1:]]
    Out[99]: 
    ['IP 123 84applemercury',
     'IP 543 65killerparsergoat',
     'IP 549 54 pineappledjangopython']
    

    If a is like

    a = ['IP 123 84', 'apple', 'mercury', 'IP 543 65', 'killer', 'parserIP', 'goat',
         'IP 549 54 pineapple', 'django', 'python']                    ^^^^
    

    the former solution won't work, you may insert some special sequence (which should never appear in a) to a, and then join & split it:

    In [11]: for i, v in enumerate(a):
        ...:     if v.startswith('IP'):
        ...:         a[i]='$$$'+v
        ...: ''.join(a).split('$$$')[1:]
    Out[11]: 
    ['IP 123 84applemercury',
     'IP 543 65killerparsergoat',
     'IP 549 54 pineappledjangopython']
    

提交回复
热议问题