0

I just started to teach myself Python, and I wanted to search an large array of strings for a couple of keywords. I tried using nested if statements but it's clunky and doesn't work.

Is there a easier way to do this? By the way, my array of strings is called tmp.

for i in range(0, len(idList)):
     for j in range(0, len(tmp)):
          if "apples" in tmp[j]: 
              if "bananas" in tmp[j]: 
                  if "peaches" in tmp[j]:
                      if "pears" in tmp[j]:
                          *Do something*
1
  • Consider doing a set comparison, Commented May 5, 2015 at 20:57

2 Answers 2

4

Your code is equivalent to:

for i in range(0, len(idList)):
     for j in range(0, len(tmp)):
          if all(s in tmp[j] for s in ("apples", "bananas", "peaches", "pears")):
               *Do something*

which makes it a bit shorter. The all() function allows you to check multiple conditions and this function evaluates to true when all conditions are true.

Sign up to request clarification or add additional context in comments.

Comments

0

From what you wrote it sounds like you're trying to find any of the keywords in the tmp list, not every in one element. If that's the case, then your code should instead be

for i in range(0, len(idList)):
    for j in range(0, len(tmp)):
        if "apples" in tmp[j]:
            *Do something*
        elif "bananas" in tmp[j]:
            *Do something*
        elif "peaches" in tmp[j]:
            *Do something*
        elif "pears" in tmp[j]:
            *Do something*

so you would do something (different or the same) in each of those conditions. If "apples" is in the current element in the list, then do something. Or, if "bananas" is in the element, then do something else.

To shorten your code, take a look at any:

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
     for element in iterable:
         if element:
             return True
     return False

This would make your code similar to Simeon's example, but replacing all for any.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.