gpt4 book ai didi

python - 过滤和获取字符串列表 block 的最快方法

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:42 25 4
gpt4 key购买 nike

我有一个巨大的标签字符串列表,应该由给定的 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

最佳答案

使用 genex 和 itertools.islice() .

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

关于python - 过滤和获取字符串列表 block 的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7622910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com