Check if substring is in a list of strings?

前端 未结 4 1856
灰色年华
灰色年华 2020-12-08 03:52

I have found some answers to this question before, but they seem to be obsolete for the current Python versions (or at least they don\'t work for me).

I want to chec

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 04:47

    The code you posted using any() is correct and should work unless you've redefined it somewhere.

    That said, there is a simple and fast solution to be had by using the substring search on a single combined string:

    >>> wordlist = ['yellow','orange','red']
    >>> combined = '\t'.join(wordlist)
    
    >>> 'or' in combined
    True
    >>> 'der' in combined
    False
    

    This should work much faster than the approach using any. The join character can be any character that doesn't occur in one of the words in the wordlist.

提交回复
热议问题