简体   繁体   English

在列表和列表中查找匹配的单词和不匹配的单词

[英]Find matching words and not matching words in a list and a list

I am beginner in learning Python and I have two lists我是学习 Python 的初学者,我有两个列表

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

and I want to find matching words and not matching words我想找到匹配的单词而不是匹配的单词

here it's example result这是示例结果

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

How can I do我能怎么做

Try:尝试:

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

This gives:这给出了:

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

Or you can use the set matching:或者您可以使用集合匹配:

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

The answered solution works perfectly well, but I would like to propose another one using the set data structure since this is the most adapted one for this kind of problem:已回答的解决方案效果很好,但我想提出另一个使用set数据结构的解决方案,因为这是最适合此类问题的解决方案:

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

set1 = set(list1)
set2 = set(list2)

matching_words = set1.intersection(set2)
# {'document', 'run'}
nonmatching_words = set1.symmetric_difference(set2)
# {'time', 'light', 'shop', 'survival', 'product'}

Please note that the order of the elements are random.请注意,元素的顺序是随机的。

However, if the order is not important, you might even want to work with sets from end to end:但是,如果顺序不重要,您甚至可能希望从头到尾使用集合:

# DECLARING A SET
set1 = {'product','document','light','time','run'}
set2 = {'survival','shop','document','run'}
# Notice the use of {} instead of []

# FOR LOOP
for word in matching_words:
    print(word)

# document
# run

If you absolutely need to have a list, you can transform back the results (order still unpredictable):如果您绝对需要一个列表,您可以将结果转换回(顺序仍然不可预测):

matching_words = list(matching_words)
nonmatching_words = list(nonmatching_words)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM