【问题标题】:How to shorten multiple IF .... IN ... OR statements? [duplicate]如何缩短多个 IF .... IN ... OR 语句? [复制]
【发布时间】:2017-05-06 17:03:14
【问题描述】:

如何缩短以下 MWE?

files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
images = [x for x in files if '.jpg' in x or '.png' in x or '.JPG' in x]
print images

我在考虑

files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
images = [x for x in files if ('.jpg' or '.png' or '.JPG') in x]
print images

这不起作用。

相对于这篇博文:Checking file extension,我也对不关注文件结尾的概括感兴趣。

【问题讨论】:

    标签: python python-2.7 list if-statement


    【解决方案1】:

    这有点短

    files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
    images = [x for x in files if x.endswith(('.jpg','.png','.JPG'))]
    print images
    

    之所以有效,是因为endswith() 可以将一个元组作为输入,如您所见in the docs

    您甚至可以这样做以使其不区分大小写

    images = [x for x in files if x.lower().endswith(('.jpg','.png'))]
    

    【讨论】:

    • 这对我的 MWE 非常有用,非常感谢。作为扩展,endswith() 是否可以替换为 ''contains()'' 之类的东西,从而更普遍地应用于不关注结尾的情况?
    • @CFW python 没有包含,但它有一个 in 关键字。在这种情况下,它将类似于 [x for x in files if any(y in x for y in ('.jpg','.png','.JPG'))] 这也将匹配例如 'abc.pngabc'
    【解决方案2】:

    怎么样:

    files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
    formats = ('.jpg', '.png', '.JPG')
    
    # this gets you the images
    images = [file for file in files if any (format in file for format in formats))
    
    # The above is equivalent to the following statement which is longer 
    # and looks complicated but probably easy to understand for someone new to [python list comprehension][1]
    images = [file for file in files if any (format for format in formats if format in file))
    

    但是,但是,如果你想检查.endswith,你应该真的使用this answer。我只是扩展了你的前提(基于你的问题,它使用了in)。

    列表理解推荐阅读:python documentation

    【讨论】:

    • 为什么不any(format in file for format in formats)
    • 当然,这是一个等效的@tobias_k。
    • @zEro:最好保留编辑后的答案并删除您之前所说的答案。另外,您可以从答案中删除 tobias_k 的名称,他不会介意;)
    • 我保留了原件,所以 OP 可以比较并了解我们在那里所做的工作。
    • 在这种情况下,最好翻转答案。重点应放在实现结果的有效方法上。因为 SO 不仅仅适用于 OP;其他人将来也会参考它:)
    【解决方案3】:

    应该这样做:

    import os
    
    files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
    images = [x for x in files if os.path.splitext(x)[-1] in   ['.jpg','.png','.JPG']]
    print images
    

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 2012-07-05
      • 1970-01-01
      • 2012-04-25
      • 2021-07-30
      相关资源
      最近更新 更多