如何创建一个for循环,以对照字典中包含的列表元素检查列表的元素?

时间:2019-08-01 19:26:00

标签: python list dictionary for-loop

我正在尝试为一系列网页标题分配主题/类别。我正在考虑先创建一个包含我需要的所有页面标题的列表,然后创建一个由主题及其相关词组成的字典(这将是一个字典,其中列表作为值,主题名称作为键)。

接下来,我想填充表格或仅以表格格式返回输出,以便我可以在Excel中对其进行操作,并且输出应在第一列中具有页面标题,而在另一列中具有主题。您能帮我完成这个任务吗?

下面我提供了一个列表和字典的示例...

page_titles = [ "How to measure insulin", "Advice for general practitioners", "Medications for HIV"]

topic_terms = { "diabetes" : ["insulin", "sugar"], "HIV" : ["HIV", "medication for HIV"] }

2 个答案:

答案 0 :(得分:0)

效率不高,但可以解决问题

outputlist = []

for page_title in page_titles:
    for topic in topic_terms:
        for keyword in topic_terms[topic]:
            if keyword in page_title:
                outputlist.append([page_title, topic])

答案 1 :(得分:0)

to_write = []
for title in page_titles:    
    for topic, rel_words in topic_terms.items():
        for word in rel_words:
            if word in title:
                to_write.append((title, topic))

to_write将是一个元组列表,其中第一项是标题,第二项是主题。用它写出您的Excel工作表。

相关问题