我有一个元组列表:
[('fruit', 'O'), ('is', 'O'), ('the', 'O'),
('subject', 'O'), ('of', 'O'), ('a', 'O'),
('Roald', 'PERSON'), ('Dahl', 'PERSON'), ('children', 'O'),
("'s", 'O'), ('book', 'O'), ('?', 'O')]`
我想将此列表缩减为:
[('fruit', 'O'), ('is', 'O'), ('the', 'O'),
('subject', 'O'), ('of', 'O'), ('a', 'O'),
('Roald Dahl', 'PERSON'), ('children', 'O'),
("'s", 'O'), ('book', 'O'), ('?', 'O')]`
即,任何连续的元组,其第二个值不是' O'应该将它们的第一个值连接起来。这适用于任何长度的列表,以及任何数量的连续元组。
def join_tags(list_tags):
res = []
last_joined = None
last_seen = (None, None)
for tup in list_tags:
if tup[1] == 'O':
res.append(tup)
last_joined = None
else:
if tup[1] == last_seen[1]:
if last_joined:
new_tup = (last_joined[0] + ' ' + tup[0], tup[1])
last_joined = new_tup
res.append(new_tup)
else:
new_tup = (tup[0] + ' ' + tup[0], tup[1])
res.append(new_tup)
last_joined = new_tup
else:
res.append(tup)
last_joined = None
last_seen = tup
return res
答案 0 :(得分:6)
如果你使用过itertools
,它有很多有用的例程用于这样的操作。一个名为groupby
的函数在这里很有用。
编辑:感谢@ juanpa.arrivillaga使用operator
improvement。
import itertools
from operator import itemgetter
r = []
for k, g in itertools.groupby(l, key=itemgetter(1)):
if k == 'O':
r.extend(g)
else:
r.append((' '.join([i[0] for i in g]), k))
print(r)
[('fruit', 'O'),
('is', 'O'),
('the', 'O'),
('subject', 'O'),
('of', 'O'),
('a', 'O'),
('Roald Dahl', 'PERSON'),
('children', 'O'),
("'s", 'O'),
('book', 'O'),
('?', 'O')]
这里,l
是元组的输入列表。