编写下面代码的python方式是什么?
extensions = ['.mp3','.avi']
file_name = 'test.mp3'
for extension in extensions:
if file_name.endswith(extension):
#do stuff
我隐约记得for循环的显式声明是可以避免的,可以写在if条件中。这是真的吗?
编写下面代码的python方式是什么?
extensions = ['.mp3','.avi']
file_name = 'test.mp3'
for extension in extensions:
if file_name.endswith(extension):
#do stuff
我隐约记得for循环的显式声明是可以避免的,可以写在if条件中。这是真的吗?
当前回答
另一种返回匹配字符串列表的方法是
sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']
其他回答
只使用:
if file_name.endswith(tuple(extensions)):
另一种可能是使用IN语句:
extensions = ['.mp3','.avi']
file_name = 'test.mp3'
if "." in file_name and file_name[file_name.rindex("."):] in extensions:
print(True)
我有这个:
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']
我在找别的东西的时候,偶然发现了这个。
我建议使用操作系统包中的方法。这是因为你可以让它更一般,弥补任何奇怪的情况。
你可以这样做:
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.