[英]Merge the first elements in a list a tuples if the second elements are the same?
我有一个元组列表:
[('Donald', 'PERSON'), ('Trump', 'PERSON'), ('enters', 'O'), ('the', 'O'), ('White', 'LOCATION'), ('House', 'LOCATION')]
我想要的输出是:
[('Donald Trump'), ('enters the'), ('White House')]
下面的代码使我更接近所需的结果,但是我还不太熟悉groupby函数。
mergedTags = []
from itertools import groupby
for tag, chunk in groupby(tagList, lambda x: x[1]):
if tag != "O":
tagMerged = " ".join(w for w, t in chunk)
mergedTags.extend([tagMerged])
else:
#tagMerged = " ".join(t for t, w in chunk)
for word, chunk in groupby(tagList, lambda x: x[0]):
mergedTags.extend([word])
print(mergedTags)
您可以将itertools.groupby
与列表理解表达式一起使用:
from itertools import groupby
my_list = [('Donald', 'PERSON'), ('Trump', 'PERSON'), ('enters', 'O'), ('the', 'O'), ('White', 'LOCATION'), ('House', 'LOCATION')]
output_list = [tuple(i[0] for i in e) for _, e in groupby(my_list, lambda x: x[1])]
# ^ generate the desired tuple
output_list
保留的值将为:
[('Donald', 'Trump'), ('enters', 'the'), ('White', 'House')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.