首页 > 解决方案 > 将字符串列表与另一个字符串列表进行比较

问题描述

positive_list = [line.strip() for line in open('positive-words.txt')] #converts text file to list
target_list = ['title', 'trump', 'impeached', 'for', 'abuse', 'of', 'power', 'two', 'weeks', 'before']

def wordcount(target_list, target_string):
    counter = 0
    for string in target_list:
        if string == target_string:
            counter += 1
        else:
            print('No matches found')
            break
    print('Number of matches: ' + counter)
wordcount(target_list, positive_list[x])  

我能够使用字符串对象搜索 target_list,但无法遍历列表 positive_list 中包含的整个字符串。

有没有办法用positive_list循环target_list?

标签: python-3.xstringlist

解决方案


您可以set用于查找匹配项:

target_set = set(target_list)
pos_set = set(positive_list)

matches = pos_set.intersection(target_set)
wordcount = len(matches)

推荐阅读