2012-01-12 46 views
0

我需要以下代碼才能在沒有線程或多處理的情況下更快完成。如果有人知道任何技巧,將不勝感激。也許for i in enumerate()或在計算之前將列表更改爲字符串,我不確定。
對於下面的例子,我試圖用隨機序列重新創建變量,但是這已經使循環內部的一些條件無用......對於這個例子來說沒問題,它只是意味着'真正'的應用程序代碼會稍微延長一點。 目前在我的i7上,下面的示例(其中大部分將繞過其中的一些條件)在1秒內完成,我希望儘可能地降低它。Python,我需要以下代碼才能更快完成

import random 
import time 
import collections 
import cProfile 


def random_string(length=7): 
    """Return a random string of given length""" 
    return "".join([chr(random.randint(65, 90)) for i in range(length)]) 

LIST_LEN = 18400 
original = [[random_string() for i in range(LIST_LEN)] for j in range(6)] 
LIST_LEN = 5 
SufxList = [random_string() for i in range(LIST_LEN)] 
LIST_LEN = 28 
TerminateHook = [random_string() for i in range(LIST_LEN)] 
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Exclude above from benchmark 


ListVar = original[:] 
for b in range(len(ListVar)): 
    for c in range(len(ListVar[b])): 

     #If its an int ... remove 
     try: 
      int(ListVar[b][c].replace(' ', '')) 
      ListVar[b][c] = '' 
     except: pass 

     #if any second sufxList delete 
     for d in range(len(SufxList)): 
      if ListVar[b][c].find(SufxList[d]) != -1: ListVar[b][c] = '' 

     for d in range(len(TerminateHook)): 
      if ListVar[b][c].find(TerminateHook[d]) != -1: ListVar[b][c] = '' 
    #remove all '' from list 
    while '' in ListVar[b]: ListVar[b].remove('') 

print(ListVar[b]) 
+0

你可以嘗試重寫代碼的某些部分在C(在列表中找到,即mstrings)。我用'swig'。此外,也許哈希,而不是列表將更快 – 2012-01-12 08:47:04

+0

你能解釋你想解決什麼問題?我們更容易回答「什麼是有效的X方法」這個問題,而不是理解你的代碼並想出一個更好的方法來實現它。 – thesamet 2012-01-12 08:51:15

+0

我想通過過濾流程運行一個列表 – Rhys 2012-01-12 08:59:31

回答

3
ListVar = original[:] 

這使得ListVar的淺表副本,讓你的第二個層次列表的變化將影響到原也。你確定這是你想要的嗎?更好的做法是從頭構建新的修改列表。

for b in range(len(ListVar)): 
    for c in range(len(ListVar[b])): 

Yuck:儘可能在列表上直接迭代。

 #If its an int ... remove 
     try: 
      int(ListVar[b][c].replace(' ', '')) 
      ListVar[b][c] = '' 
     except: pass 

你想忽略數字中間的空格嗎?這聽起來不對。如果數字可能爲負值,您可能需要使用try..except,但如果它們只是正值,則只需使用.isdigit()

 #if any second sufxList delete 
     for d in range(len(SufxList)): 
      if ListVar[b][c].find(SufxList[d]) != -1: ListVar[b][c] = '' 

這是不是很糟糕的命名? SufxList意味着你正在尋找後綴,如果是的話,只需使用.endswith()(注意你可以傳入一個元組來避免循環)。如果您確實想要查找字符串中任何位置的後綴,請使用in運算符。

 for d in range(len(TerminateHook)): 
      if ListVar[b][c].find(TerminateHook[d]) != -1: ListVar[b][c] = '' 

再次使用in運算符。另外any()在這裏很有用。

#remove all '' from list 
    while '' in ListVar[b]: ListVar[b].remove('') 

while是O(n^2),即,將是緩慢的。您可以使用列表理解,而不是去除空白,但更好的是建立乾淨的列表開始。

print(ListVar[b]) 

我想也許你的縮進在那張印刷上是錯誤的。

把這些建議一起給出類似:

suffixes = tuple(SufxList) 
newListVar = [] 
for row in original: 
    newRow = [] 
    newListVar.append(newRow) 
    for value in row: 
     if (not value.isdigit() and 
      not value.endswith(suffixes) and 
      not any(th in value for th in TerminateHook)): 
      newRow.append(value) 

    print(newRow) 
+0

感謝您的好評 – Rhys 2012-01-12 19:07:26

相關問題