根据列表中的条件合并列表项 [英] Merge list items based on condition within the list
本文介绍了根据列表中的条件合并列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个项目清单: 例如:
I have a list of items : eg:
a = ['IP 123 84', 'apple', 'mercury', 'IP 543 65', 'killer', 'parser', 'goat',
'IP 549 54 pineapple', 'django', 'python']
我想根据条件合并列表项目,即合并所有项目,直到以IP开头的项目. 我想要的输出是:
I want to merge the list items based on condition i.e merge all the items till the item that starts with IP. The output I want is :
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']
这篇关于根据列表中的条件合并列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文