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

后端 未结 2 1015
野性不改
野性不改 2021-01-29 13:30

I am beginner in learning Python and I have two lists

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


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-29 14:03

    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))
    

提交回复
热议问题