我有一個函數,它接受一個列表並返回列表ngrams
(這裏n = 2)。我該如何平行化這個功能,以減少運行時間?如何在Python中使用一個參數並行化一個函數?
我正在嘗試這個,但它不工作。 data_list
是一個字符串列表。
import multiprocessing
from multiprocessing.dummy import Pool
from collections import OrderedDict
grams_list = []
data_list = ["Hello, I am learning Python",
"Python is a very Powerful language",
"And Learning python is easy" ]
def ngrams(input, n):
input = input.split(' ')
output = []
for i in range(len(input) - n + 1):
output.append(input[i:i + n])
return output
def generating_grams_list(data_list):
for j in range(0, len(data_list)):
grams = [' '.join(x) for x in ngrams(data_list[j], 2)] # Creating ngrams
grams_list.append(list(OrderedDict.fromkeys(grams))) # removing duplicates
# print "Creating ngrams list for each data string ", j
return grams_list
if __name__ == '__main__':
pool = Pool(multiprocessing.cpu_count())
results = pool.map(generating_grams_list, data_list)
pool.close()
pool.join()
for result in results:
print("result", result)
什麼不正確?有錯誤嗎?結果是否與預期不符?使用'dummy'模塊,你不會得到任何並行化。並行性與並行性並不相同 – karlson
@karlson結果與預期不符 – sahil
爲什麼不擴展您的問題,結果如何,以及您會期望什麼? – karlson