简体   繁体   中英

Find matching words and not matching words in a list and a list

I am beginner in learning Python and I have two lists

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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