0

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!

  • 1
    Half-joking answer: wait and see if [assignment expressions](https://www.python.org/dev/peps/pep-0572/) get integrated into a future version of the language. Capturing a witness from an any() expression is explicitly one of the feature's motivations :-) – Kevin Jun 05 '18 at 18:29

2 Answers2

2

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...')
nosklo
  • 217,122
  • 57
  • 293
  • 297
1

You can use next((search for search in look_for if (search in i)), None) to get the first matching element. It's still short-circuiting so it will stop searching after it finds a match. If no match is found, the second argument will be returned.

recursive
  • 83,943
  • 34
  • 151
  • 241