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

2024-10-03 02:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python列表:

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

我想做一些类似的事情(使用伪javascript):

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

在python中最整洁的方法是什么?我找不到some函数!你知道吗


Tags: 列表returnifhtmljsfunctionsomejavascript
3条回答

总的来说

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的答案。你知道吗

也许是这样的?你知道吗

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

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

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

如果以任何给定的扩展名结束,则返回True。你知道吗

相关问题 更多 >