Check if substring is in a list of strings?

前端 未结 4 1806
灰色年华
灰色年华 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:25

    You can import any from __builtin__ in case it was replaced by some other any:

    >>> from  __builtin__ import any as b_any
    >>> lst = ['yellow', 'orange', 'red']
    >>> word = "or"
    >>> b_any(word in x for x in lst)
    True
    

    Note that in Python 3 __builtin__ has been renamed to builtins.

    0 讨论(0)
  • 2020-12-08 04:26

    Also if someone wants to check if any of the values of a dictionary exists as a substring in a list of strings, can use this:

    list_a = [
        'Copy of snap-009ecf9feb43d902b from us-west-2',
        'Copy of snap-0fe999422014504b6 from us-west-2',
        'Copy of snap-0fe999422014cscx504b6 from us-west-2',
        'Copy of snap-0fe999422sdad014504b6 from us-west-2'
    ]
    dict_b = {
        '/dev/xvda': 'snap-0fe999422014504b6',
        '/dev/xvdsdsa': 'snap-sdvcsdvsdvs'
    }
    
    for b1 in dict_b.itervalues():
        result = next( ("found" for a1 in a if b1 in a1), "not found")
        print result 
    

    It prints

    not found
    found
    
    0 讨论(0)
  • 2020-12-08 04:39

    You could use next instead:

    colors = ['yellow', 'orange', 'red'] 
    search = "or"
    
    result = next((True for color in colors if search in color), False)
    
    print(result) # True
    

    To show the string that contains the substring:

    colors = ['yellow', 'orange', 'red'] 
    search = "or"
    
    result = [color for color in colors if search in color]  
    
    print(result) # Orange
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题