使用带有多个扩展名的endswith

Gui*_*ume 28 python file list

我正在尝试检测带有扩展名列表的文件.

ext = [".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", \
                        ".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", \
                        ".rm", ".swf", ".vob", ".wmv"]
if file.endswith(ext): # how to use the list ?
   command 1
elif file.endswith(""): # it should be a folder
   command 2
elif file.endswith(".other"): # not a video, not a folder
   command 3
Run Code Online (Sandbox Code Playgroud)

Suk*_*lra 71

使用元组.

>>> ext = [".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", \
                        ".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", \
                        ".rm", ".swf", ".vob", ".wmv"]

>>> ".wmv".endswith(tuple(ext))
True
>>> ".rand".endswith(tuple(ext))
False
Run Code Online (Sandbox Code Playgroud)

而不是每次转换,只需将其转换为元组一次.


小智 7

难道你不能在一开始就把它变成元组吗?你为什么要这样做:

>>> ".wmv".endswith(tuple(ext))
Run Code Online (Sandbox Code Playgroud)

你不能这样做:

>>> ext = (".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", \
                        ".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", \
                        ".rm", ".swf", ".vob", ".wmv")
Run Code Online (Sandbox Code Playgroud)