您也可以使用 filter() 代替列表推导式,这可能具有您可以轻松交换过滤器功能以获得更大灵活性的优势:
>>> l1 = ['test1', 'test2', 'test3', 'test4', 'test5']
>>> l2 = set(['*t1*', '*t4*'])
>>> filterfunc = lambda item: not any(fnmatch(item, pattern) for pattern in l2)
>>> filter(filterfunc, l1)
Out: ['test2', 'test3', 'test5']
>>> # now we don't like our filter function no more, we assume that our l2 set should match on any partial match so we can get rid of the star signs:
>>> l2 = set(['t1', 't4'])
>>> filterfunc = lambda item: not any(pattern in item for pattern in l2)
>>> filter(filterfunc, l1)
Out: ['test2', 'test3', 'test5']
这样,您甚至可以泛化您的 filterfunc 以使用多个模式集:
>>> from functools import partial
>>> def filterfunc(item, patterns):
return not any(pattern in item for pattern in patterns)
>>> filter(partial(filterfunc, patterns=l2), l1)
Out: ['test2', 'test3', 'test5']
>>> filter(partial(filterfunc, patterns={'t1','test5'}), l1)
Out: ['test2', 'test3', 'test4']
当然,您可以轻松升级您的 filterfunc 以接受模式集中的正则表达式。