任何字符串列表中我有一个字符串列表,从中我要找到每一个具有行的“http://”在里面,但没有“lulz”,“ LMFAO“”巴纽”,或在它的字符串列表其他任何物品。我会怎么做呢?如果字符串不包含在python
我的直觉告诉我,使用正则表达式,但我有道义上的反对巫术。
任何字符串列表中我有一个字符串列表,从中我要找到每一个具有行的“http://”在里面,但没有“lulz”,“ LMFAO“”巴纽”,或在它的字符串列表其他任何物品。我会怎么做呢?如果字符串不包含在python
我的直觉告诉我,使用正则表达式,但我有道义上的反对巫术。
这里是一个还算可扩展的,如果字符串排除列表是大的选项:
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)]
试试这个:
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
这是我的第一个方法。但随着我的长大名单和行变得笨拙,我希望有一个更好的办法。 – directedition 2012-03-08 01:06:09
这可能失控,如果他想延长停止词列表。你会如何改变你的方法?但是,对于简单的解决方案,还是+1 – prelic 2012-03-08 01:06:18
这几乎等同于FJ的解决方案,但使用generator expressions代替lambda表达式和过滤功能:
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']
发电机+1。但是,请注意,您可以将其作为(几乎)单行程:'result_strings = [s for s in haystack if s.startswith('http://')and any any(in in for in in exclude )]'。它需要一个换行符合80列(按照大多数风格指南),但我认为它比双发生器版本稍微容易一些。 timeit还报告说,这比FJ的过滤器版本(IMO,这是三者中最难遵循的版本)稍微快一点,并且也稍微快一些。 – lvc 2012-03-08 01:43:37
太棒了!我开始使用lambda!我知道它存在是有原因的! – directedition 2012-03-08 01:23:12
你不需要。 'lambda'允许你定义内联函数,而不是设置一个变量'filter_func';但是你可以很容易地编写'高清filter_func(S):返回的“http://”在S和没有任何(X在S代表X中排除)'。请记住,函数是对象。 – 2012-03-08 02:46:13
我甚至会说这是对'lambda'的不当使用。在这里没有理由选择“def”。 – wim 2012-03-08 03:42:38