Search code examples
pythonlistmatchany

Python use of any(), which one matches?


I'm writing a script to sort logfiles into more convenient data and to do so I use the any() function. I now know if part of a string matches any of the items in my list. Here's the function:

    def logfiles(self):

    look_for = ['network', 'skip', 'remove', 'jitter', 'loss', 'diff']
    analyze = self.open_logs('logfile-1.log')
    result = []

    for i in analyze:
        i = i.strip()

        if any(search in i for search in look_for):
            result.append(i)

    return result

This will tell me if part of the string i matches any of the items in my list look_for. However, is there a way to also detect which item matches? I haven't been able to find a built-in way for any() to do so and don't think there is one so how would one go about solving this? This particular snippet is a lot faster than a previous method I used (a simple loop basically) so I'd prefer to continue using this..

Thanks!


Solution

  • By using any, you're semantically discarding the return value. You don't care which one, you just care that if any of them is true.

    I suggest using a explicit for, instead. It is clearer, and removes the complexity of a obscure next() with exception handling. Performance is the same:

    for search in look_for:
        if search in i:
            break
    else:
        print('Not found...')