首页 > 解决方案 > 在列表和列表中查找匹配的单词和不匹配的单词

问题描述

我是学习 Python 的初学者,我有两个列表

list1 = ['product','document','light','time','run']
list2 = ['survival','shop','document','run']

我想找到匹配的单词而不是匹配的单词

这是示例结果

matching_words = ['document','run']
notmatching_words = ['product','light','time','survival','shop']

我能怎么做

标签: pythonpython-3.x

解决方案


尝试:

matching_words = []
notmatching_words = list(list2) # copying the list2
for i in list1:
    if i in list2:
        matching_words.append(i) # appending the match
        notmatching_words.remove(i) # removing the match
    else:
        notmatching_words.append(i) # appending the un-matched

这给出了:

>>> matching_words
['document', 'run']
>>> notmatching_words
['survival', 'shop', 'product', 'light', 'time']

或者您可以使用集合匹配:

matching_words = list (set(list1) & set(list2)) # finds elements existing in both the sets
notmatching_words = list(set(list1) ^ set(list2))

推荐阅读