2015-12-01 27 views
1

我的列表中有大量的文本數據,而且我的問題發現特定的值太慢。因爲我必須從列表中找到50個以上的關鍵字。使用線程在列表中查找特定值

這裏我的工作腳本:

for num, line in enumerate(MyList): 
    passList = [] 
    if "pass" in line: 
     passList.append(line)   

    failedList = [] 
    if "failed" in line: 
     failedlist.append(line) 

    doneList = [] 
    if "done" in line: 
     doneList.append(line) 

    #.. 
    #... 
    #....more and more conditions here 

有沒有辦法有一個快速的執行,或者使用線程,如果沒有其他的解決方案。

任何建議/意見,在此先感謝..

+0

你爲什麼不解析線和檢查,如果你正在尋找的字是在準確的位置?請顯示該行的格式。 – thefourtheye

+0

你可以使用grep嗎?這當然更快。 – fiacre

+0

@thefourtheye,我正在找到確切的值,現在我只是使用該虛擬字符串來查找,但實際上在我的if條件下它也在列表中。 –

回答

0

的問題是,你是爲每個關鍵字做的每一行進行完全掃描一次。你想在一次掃描中找到你的匹配。正則表達式會更有效地做到這一點。簡單地構建,其中包括所有的按鍵和匹配反對正則表達式模式:

keys = ('foo', 'bar', 'stat', 'key', 'abcd', 'efgh', '$') 
pattern = re.compile("(%s)" % "|".join(keys)) 

data = [ 
    'this is foo', 
    'this is bar', 
    'this is abcd', 
    'this is efgh', 
    'this is no match' 
] 

results = defaultdict(list) 
for string in data: 
    match = pattern.search(string) 
    results[match.group(1)].append(string) 

print results 
+0

我在這裏得到了你的觀點,但現在我試圖分析從列表中找到50多個特定關鍵字是否會很快。 –

+0

和?我很好奇看到結果。我懷疑你會得到改善。但是,改進的程度取決於數據的性質和密鑰。 –