How to check if my list has an item from another list(dictionary)?

前端 未结 2 874
清歌不尽
清歌不尽 2021-01-26 12:38

I\'m a beginner in programming with python, and I\'ve got a question which may have an easy answer.

So I have a dictionary of words which is imported from a .txt file, n

2条回答
  •  一生所求
    2021-01-26 13:15

    Using sets

    You could use sets to find all of the words not in the dictionary list.

    >>> set([1,2,3]).difference([2,3])
    set([1])
    

    Note that this will not include duplicates.

    So for you, it would be something like this (if you need the result to be a list):

    misspelled_word_list = list( set(sentence_list).difference(words) )
    

    Using for

    Since you are required to use for, here is an alternate (less efficient) approach:

    misspelled_word_list = []
    for word in sentence_list:
        if (not word in misspelled_word_list) and (not word in words):
            misspelled_word_list.append(word)
    

    You just loop over the words in sentence_list and check whether they are in your words list or not.

提交回复
热议问题