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

后端 未结 2 1014
野性不改
野性不改 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)
    

提交回复
热议问题