我有一个巨大的标记字符串列表,应该由给定的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 。
答案 0 :(得分:3)
使用genex和itertools.islice()
。
'\n'.join(itertools.islice((tag for tag in tags if tag.startswith(tag_filter)), 20))
答案 1 :(得分:1)
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))))
修改:实际上,由于list
,join
调用是不必要的,因此只需使用islice
,因为在Ignacio的答案中就足够了。