Python-合并嵌套列表中的元组列表

时间:2018-11-07 20:23:12

标签: python python-3.x

我有要合并的元组列表。下面的代码将属性与传递给“ classified_text”的单个列表结合在一起,如何为嵌套元组列表迭代此概念?我尝试添加另一个for循环和append方法,但是出现了不同的错误。有任何简单的方法吗?谢谢!

输入文本1-工作:

classified_text = [('John', 'PERSON'), ('Smith', 'PERSON'),('University', 'ORGANIZATION'), ('of', 'ORGANIZATION'), ('ABC', 'ORGANIZATION')] # Single list

输出文本1-工作:

[('PERSON      ', 'John Smith'), ('ORGANIZATION', 'University of ABC')]

输入文本2-不起作用:带有元组的嵌套列表

classified_text = [[('John', 'PERSON'), ('Smith', 'PERSON')], [('University', 'ORGANIZATION'), ('of', 'ORGANIZATION'), ('ABC', 'ORGANIZATION')], [('some', 'O'), ('text', 'O'), ('here', 'O')], [('Mark', 'O'), ('from', 'O'), ('University', 'ORGANIZATION'), ('of', 'ORGANIZATION'), ('CA', 'ORGANIZATION')]]

代码:

from itertools import groupby
entity_extracted_words = []
for tag, chunk in groupby(classified_text, lambda x:x[1]):
    if tag != "O":
        info_ner = "%-12s"%tag, " ".join(w for w, t in chunk)
        entity_extracted_words.append(info_ner)

print('entity_extracted_words:\n', entity_extracted_words)

文本2-尝试获得以下结果:

[('PERSON      ', 'John Smith'), ('ORGANIZATION', 'University of ABC'),('ORGANIZATION', 'University of CA')] 

错误: TypeError:不是所有在格式化字符串期间转换的参数

2 个答案:

答案 0 :(得分:2)

尝试类似这样的方法。只需在hasOwnPropertyfor-loop,组合成一个字符串并将其添加到sublist

newlist

答案 1 :(得分:0)

您可以先将列表列表平化为一个列表:

flat_list = [item for sublist in classified_text for item in sublist]

该清单应与您的原始代码配合使用。