[英]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/
有很多點需要說明:
你的 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.