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

后端 未结 2 1013
野性不改
野性不改 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 13:54

    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)
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
提交回复
热议问题