【问题标题】:Python - If statement to check against a range of choices an [duplicate]Python - If 语句检查一系列选择 [重复]
【发布时间】:2018-11-26 21:47:33
【问题描述】:

我遍历文件列表并想在处理之前检查它们是否具有许多扩展名之一。是否有可能避免这两种情况? - 通过 OR 语句检查每个扩展(即硬编码) - 循环中的循环

到目前为止构建:

#Iterate over files
for filename in os.listdir(os.getcwd()+dataDir):
    #iterate over ext (want to avoid)
    for u in ['jpg','txt'] :
        if filename.endswith(u):
            print("An ext of my choice found!")
        continue
    else:
        continue

提前致谢。 问候, 圣达雷什

【问题讨论】:

  • 您考虑过使用字典吗?这对于 Python 不需要的 case/switch 语句非常有用。我会用字典试试。
  • @Sufiyan Ghori - 感谢您提醒我注意重复 - any() 回答了我的问题并提供了一种漂亮的方式。

标签: python if-statement


【解决方案1】:

我认为你正在做的很好。我建议的唯一改变是风格,以确保你的 for 循环的目的不是多个缩进。此外,在这种特殊情况下,else 部分不是必需的。

#Iterate over files
for filename in os.listdir(os.getcwd()+dataDir):
    #iterate over ext (want to avoid)
    for u not in ['jpg','txt']:
        continue
    if not filename.endswith(u):
        continue
    print("An ext of my choice found!")

【讨论】:

  • 谢谢,我觉得 any() 函数(在另一个注释中)回答了我的问题,但我们非常感谢您关于将缩进数量保持在最低限度的建议。
猜你喜欢
  • 2018-09-09
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
  • 2019-10-22
  • 2019-06-30
  • 2019-01-12
相关资源
最近更新 更多