LIST=['insert_job: aaa', 'box_name: bbb', 'insert_job: ccc',
'box_name: ddd', 'insert_job: eee', 'insert_job: fff',
'box_name: ggg']
在上面的列表中,如果有2个连续insert_job: ('insert_job: eee', 'insert_job: fff')
,那么我想首先打印insert_job:
,在这种情况下将insert_job: eee
。
答案 0 :(得分:1)
您可以使用itertools.groupby
from itertools import groupby
LIST = ['insert_job: aaa', 'box_name: bbb', 'insert_job: ccc',
'box_name: ddd', 'insert_job: eee', 'insert_job: fff',
'box_name: ggg']
for k, g in groupby(LIST, lambda s: s.split(':')[0]):
if k == 'insert_job':
items = list(g)
if len(items) > 1:
print(*items[:-1])
答案 1 :(得分:0)
因为你需要物品的顺序,所以你不需要字典。尝试以下内容
seen = 0
for i in LIST:
if i.startswith("insert_job"):
if seen:
continue
else:
seen = 1
print i
else:
seen=0
# print i