Python 筛选和获取字符串列表块的最快方法
我有一个庞大的标签字符串列表,这些字符串应该由给定的标签过滤器过滤。Python 筛选和获取字符串列表块的最快方法,python,list,Python,List,我有一个庞大的标签字符串列表,这些字符串应该由给定的标签过滤器过滤。 返回的连接字符串应包含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,
返回的连接字符串应包含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,使用genex和 使用genex和 见: 那么你的情况呢
return '\n'.join(take(20, (tag for tag in tags if tag.startswith(tag_filter))))
编辑:实际上,在这种情况下,列表
调用是不必要的,因为加入
,所以只要像Ignacio的回答那样使用islice
就足够了。请参阅:
那么你的情况呢
return '\n'.join(take(20, (tag for tag in tags if tag.startswith(tag_filter))))
Edit:实际上,在这种情况下,list
调用是不必要的,因为join
所以只要像Ignacio的回答那样使用islice
就足够了
return '\n'.join(take(20, (tag for tag in tags if tag.startswith(tag_filter))))