我有一个项目清单:例如:
a = ['IP 123 84', 'apple', 'mercury', 'IP 543 65', 'killer', 'parser', 'goat',
'IP 549 54 pineapple', 'django', 'python']
我想根据条件合并列表项,即合并所有项,直到以IP开头的项。我想要的输出是:
a = ['IP 123 84 apple mercury', 'IP 543 65 killer parser goat',
'IP 549 54 pineapple django python']
请提出建议。
使用发电机。
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']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句