Andrew
Andrew

Reputation: 23

If any item in a list is contained

I have a script that iterates through a list of files in a directory. Based on words inside the filenames, it would categorize them into three groups. To complicate things, there are now exceptions to this. The exceptions are in a list. My problem is that I can't get it to check for "any" of the items in the list, and if not there, continue to categorize. The excepted word can be anywhere in the filename. I can get it to find things in the list and do something using a for loop, but it'll then move to the next iteration and ignore the previous excepted word and categorize it incorrectly.

This is how I want it to work, but the any( doesn't work like this apparently.

exceptions = ["one", "two", "three"]
for i in filenames:
   if any(exceptions) in i:
      do this
   else:
      do this

Upvotes: 2

Views: 61

Answers (3)

Rashed Rahat
Rashed Rahat

Reputation: 2475

Here is solution:

filenames = ['foo', 'bar']
 
exceptions = ['one', 'two', 'three']

check =  any(item in exceptions for item in filenames)
 
if check is True:
    print("The list {} contains some elements of the list {}".format(filenames, exceptions))    
else :
    print("No, filenames doesn't have any elements of the exceptions.")

Happy coding :)

Upvotes: 2

will-hedges
will-hedges

Reputation: 1284

You could use 3 separate if/elif statements if your number of exceptions/conditions is minimal and you want to handle each exception differently:

for i in filenames:
   if "one" in i:
      categorize_as_one
   elif "two" in i:
      categorize_as_two
   elif "three" in i:
      categorize_as_three
   else:
      pass

However, if your list of exceptions is quite long and you only want to capture if any exception is present and group those filenames together, @zipa's answer is way cleaner.

Upvotes: 1

zipa
zipa

Reputation: 27869

This will do it:

exceptions = ["one", "two", "three"]
for i in filenames:
   if any(e in i for e in exceptions):
      do this
   else:
      do this

Upvotes: 2

Related Questions