Python 使用带有多个扩展名的 endwith
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22812785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:45:08 来源:igfitidea点击:
Use endswith with multiple extensions
提问by Guillaume
I'm trying to detect files with a list of extensions.
我正在尝试检测具有扩展名列表的文件。
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
采纳答案by Sukrit Kalra
Use a tuple for it.
使用元组。
>>> 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
Instead of converting everytime, just convert it to tuple once.
而不是每次都转换,只需将其转换为元组一次。
回答by Patrick
Couldn't you have just made it a tuple in the first place? Why do you have to do:
你不能首先把它变成一个元组吗?为什么你必须这样做:
>>> ".wmv".endswith(tuple(ext))
Couldn't you just do:
你不能只做:
>>> ext = (".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", \
".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", \
".rm", ".swf", ".vob", ".wmv")