I’m working with a code snippet that iterates over an object list and filters out objects to perform a specific task. The for
loop consists of multiple nested if
statements (and I’ll probably add more in the future).
Here’s my code:
JavaScript
x
9
1
for obj in objects:
2
if 'x' not in obj.name:
3
if 'y' not in obj.name:
4
if 'z' not in obj.name:
5
if obj.length > 0:
6
if obj.is_directory == True:
7
8
# Do Something
9
Is there a neat or efficient workaround for this snippet?
Please Advise
Advertisement
Answer
You can also write:
JavaScript
1
4
1
for obj in objects:
2
if not any(c in obj.name for c in 'xyz') and obj.length > 0 and obj.is_directory:
3
# Do something
4
In case x
, y
and z
are not single characters the solution remains the same. A string in Python is a sequence of characters, so you can substitute the 'xyz'
string with the sequence (list) of words. You can put any iterable in there as well.
JavaScript
1
4
1
for obj in objects:
2
if not any(w in obj.name for w in [word1, word2, word3]) and obj.length > 0 and obj.is_directory:
3
# Do something
4