Compare string with all values in array

前端 未结 4 729
小鲜肉
小鲜肉 2020-12-09 02:54

I am trying to fumble through python, and learn the best way to do things. I have a string where I am doing a compare with another string to see if there is a match:

4条回答
  •  时光取名叫无心
    2020-12-09 03:34

    for word in d:
        if d in paid[j]:
             do_something()
    

    will try all the words in the list d and check if they can be found in the string paid[j].

    This is not very efficient since paid[j] has to be scanned again for each word in d. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.

    sentence = "words don't come easy"
    d = ["come", "together", "easy", "does", "it"]
    
    s1 = set(sentence.split())
    s2 = set(d)
    
    print (s1.intersection(s2))
    

    Output:

    {'come', 'easy'}
    

提交回复
热议问题