繁体   English   中英

在 Python 中迭代列表并找到合适的字符串模式的最快(最有效)方法是什么?

[英]What's the fastest (most efficient) way to iterate through a list and find a fitting string pattern in Python?

所以我有一个看起来像这样的字符串列表 -

['https://images.website.com/images/data/X/source1',
'https://images.website.com/articles/data/main_data/source2',
'https://images.website.com/harmony/data/Y/source3',
'https://images.website.com/files/data/Z/source4',
'https://images.website.com/pictures/data/T/source5']

我需要找到其中包含 main_data 的项目。

我想到了类似的东西。


def func():
    for item in list:
        if item.index('/main_data/'):   # not -1 
            return item

return -1  # item not found

当我有 100-1000 个甚至更多项目的列表时,这是最快的方法吗?

如果您提到的只有 100-1000 个项目,我想您已经为我们发布的方法会立即完成,因此很难想象加快速度带来的可感知收益。 但是,如果您有更多项目,如果可能的话,在 for 循环上使用内置 function 通常更快。

def func(l):
    return next(filter(lambda s: '/main_data/' in s, l))
    # raises StopIteration if no string contains /main_data/

有很多点需要说明:

  • 如果您关心性能,请不要将 Python 用于该位。
  • 如果您可以使用多个核心,请这样做。 该任务是令人尴尬的并行,尽管您可能需要将线程保留在池中,因为项目很少。
  • 如果您大致知道 substring 在字符串中的位置,那么您可以避免遍历整个字符串。 与猜测字符串通常在列表中的 position 相同。
  • 如果您有一些关于允许您减少搜索的属性的信息,请使用它。
  • 如果您需要多次搜索,也许是针对不同的术语,您可能能够构建更好的数据结构或索引,而不是每次都执行简单的搜索。

你的 function 最快

def func_1(path_list):
     for item in path_list:
         if '/main_data/' in item:
             return item
     return -1  

例如,对于 100 个元素,时间处理为 0:00:00.000048,这很好。

path_list = 99*['https://images.website.com/images/data/X/source1']
path_list.append('https://images.website.com/articles/data/main_data/source2')

from datetime import datetime

now = datetime.now()

func_1(path_list)

end = datetime.now()
print(end-now)

0:00:00.000048

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM