如何减少Python中的多个嵌套if语句?

Luk*_*uke 2 python python-3.x

我正在使用一个代码片段,该代码片段迭代对象列表并过滤掉对象以执行特定任务。该for循环由多个嵌套if语句组成(我将来可能会添加更多)。

这是我的代码:

for obj in objects:
  if 'x' not in obj.name:
    if 'y' not in obj.name:
      if 'z' not in obj.name:
        if obj.length > 0:
          if obj.is_directory == True:
            
            # Do Something
Run Code Online (Sandbox Code Playgroud)

这个片段有一个简洁或有效的解决方法吗?

请指教

use*_*849 5

你也可以写:

for obj in objects:
   if not any(c in obj.name for c in 'xyz') and obj.length > 0 and obj.is_directory:
      # Do something
Run Code Online (Sandbox Code Playgroud)

如果xyz不是单个字符,则解决方案保持不变。Python 中的字符串是字符序列,因此您可以'xyz'用单词序列(列表)替换字符串。您也可以将任何可迭代对象放在那里。

for obj in objects:
   if not any(w in obj.name for w in [word1, word2, word3]) and obj.length > 0 and obj.is_directory:
      # Do something
Run Code Online (Sandbox Code Playgroud)