2012-02-10 7 views
0

私はpythonでこのリストを持っている:リスト内のすべての値について関数をテストしますか?

fileTypesToSearch = ['js','css','htm', 'html'] 

と私は(疑似JavaScriptを使用して)のような何かをしたい:

if (fileTypesToSearch.some(function(item){ return fileName.endsWith(item); })) 
    doStuff(); 

pythonでこれを行うにneatest方法は何ですか? some機能が見つかりません!

答えて

6

、あなたはany()を探しているかもしれないが、この特定のケースでは、あなただけのstr.endswith()が必要になります。それは与えられた拡張子のいずれかで終わる場合

filename.endswith(('js','css','htm', 'html')) 

Trueを返します。

+0

ああ、それは本当に両方のカウントに便利です。ありがとう。 – Oliver

3

多分このような何か?一般的に

fileTypesToSearch = ['js', 'css', 'htm', 'html'] 
if any([fileName.endswith(item) for item in fileTypesToSearch]): 
    doStuff() 
+3

anyの中にlistcompは必要ありません。 – DSM

1

一般的には、

strings = ['js','css','htms', 'htmls'] 
if all(s.endswith('s') for s in strings): 
    print 'yes' 

または

strings = ['js','css','htm', 'html'] 
if any(s.endswith('s') for s in strings): 
    print 'yes' 

が、この場合にはSvenの答えを参照してください。

関連する問題