编写下面代码的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条件中。这是真的吗?
当前回答
我有这个:
def has_extension(filename, extension):
ext = "." + extension
if filename.endswith(ext):
return True
else:
return False
其他回答
只使用:
if file_name.endswith(tuple(extensions)):
虽然并不广为人知,但str.endswith也接受元组。你不需要循环。
>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True
另一种可能是使用IN语句:
extensions = ['.mp3','.avi']
file_name = 'test.mp3'
if "." in file_name and file_name[file_name.rindex("."):] in extensions:
print(True)
另一种返回匹配字符串列表的方法是
sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']
我有这个:
def has_extension(filename, extension):
ext = "." + extension
if filename.endswith(ext):
return True
else:
return False