如果字符串不包含python中的任何字符串列表

2024-04-16 16:57:54 发布

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


Tags: python
3条回答

这几乎等同于F.J的解,但使用generator expressions而不是lambda表达式和filter函数:

haystack = ['http://blah', 'http://lulz', 'blah blah', 'http://lmfao']
exclude = ['lulz', 'lmfao', '.png']

http_strings = (s for s in haystack if s.startswith('http://'))
result_strings = (s for s in http_strings if not any(e in s for e in exclude))

print list(result_strings)

当我运行它时,它会打印:

['http://blah']

试试这个:

for s in strings:
    if 'http://' in s and not 'lulz' in s and not 'lmfao' in s and not '.png' in s:
        # found it
        pass

其他选项,如果您需要更灵活的选项:

words = ('lmfao', '.png', 'lulz')
for s in strings:
    if 'http://' in s and all(map(lambda x, y: x not in y, words, list(s * len(words))):
        # found it
        pass

如果要排除的字符串列表很大,这里有一个相当可扩展的选项:

exclude = ['lulz', 'lmfao', '.png']
filter_func = lambda s: 'http://' in s and not any(x in s for x in exclude)

matching_lines = filter(filter_func, string_list)

列表理解选项:

matching_lines = [line for line in string_list if filter_func(line)]

相关问题 更多 >