编写下面代码的python方式是什么?

extensions = ['.mp3','.avi']
file_name = 'test.mp3'

for extension in extensions:
    if file_name.endswith(extension):
        #do stuff

我隐约记得for循环的显式声明是可以避免的,可以写在if条件中。这是真的吗?


当前回答

我在找别的东西的时候,偶然发现了这个。

我建议使用操作系统包中的方法。这是因为你可以让它更一般,弥补任何奇怪的情况。

你可以这样做:

import os

the_file = 'aaaa/bbbb/ccc.ddd'

extensions_list = ['ddd', 'eee', 'fff']

if os.path.splitext(the_file)[-1] in extensions_list:
    # Do your thing.

其他回答

只使用:

if file_name.endswith(tuple(extensions)):

虽然并不广为人知,但str.endswith也接受元组。你不需要循环。

>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True

我在找别的东西的时候,偶然发现了这个。

我建议使用操作系统包中的方法。这是因为你可以让它更一般,弥补任何奇怪的情况。

你可以这样做:

import os

the_file = 'aaaa/bbbb/ccc.ddd'

extensions_list = ['ddd', 'eee', 'fff']

if os.path.splitext(the_file)[-1] in extensions_list:
    # Do your thing.

我有这个:

def has_extension(filename, extension):

    ext = "." + extension
    if filename.endswith(ext):
        return True
    else:
        return False

另一种返回匹配字符串列表的方法是

sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']