测试列表中所有值的函数?

时间:2012-02-10 16:47:42

标签: python

我在python中有这个列表:

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

我想做(使用伪javascript):

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

在python中执行此操作的最佳方法是什么?我找不到some函数!

3 个答案:

答案 0 :(得分:6)

一般情况下,您可能正在寻找any(),但在这种特殊情况下,您只需要str.endswith()

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

以任何给定的扩展名结束,

将返回True

答案 1 :(得分:3)

也许是这样的?

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

答案 2 :(得分: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的答案。