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)
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)]
这几乎等同于F.J的解,但使用generator expressions而不是lambda表达式和filter函数:
当我运行它时,它会打印:
试试这个:
其他选项,如果您需要更灵活的选项:
如果要排除的字符串列表很大,这里有一个相当可扩展的选项:
列表理解选项:
相关问题 更多 >
编程相关推荐