最快的方法来过滤并获取一大串字符串

时间:2011-10-01 20:54:32

标签: python list

我有一个巨大的标记字符串列表,应该由给定的tag_filter过滤 返回的连接字符串应包含20个最大标记\n。 现在,代码看起来像这样:

tags = Tag.get_tags() #This returns the list of tags strings
return '\n'.join([tag for tag in tags if tag.startswith(tag_filter)][:20])

如何改进它,避免在匹配20个标签后扫描所有标签列表? 我正在使用 Python 2.5

2 个答案:

答案 0 :(得分:3)

使用genex和itertools.islice()

'\n'.join(itertools.islice((tag for tag in tags if tag.startswith(tag_filter)), 20))

答案 1 :(得分:1)

请参阅itertools recipies

def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))

所以在你的情况下

return '\n'.join(take(20, (tag for tag in tags if tag.startswith(tag_filter))))

修改:实际上,由于listjoin调用是不必要的,因此只需使用islice,因为在Ignacio的答案中就足够了。