簡體   English   中英

Python 中的並行/多處理(嵌套)循環並存儲結果?

[英]Parallel/multiprocessing (nested) loops in Python and storing the results?

我有兩個問題,我認為它們足夠相關,可以成為一個問題的一部分。 但如果不是,我可以將它們作為單獨的問題提出。 請告訴我。 我也提前道歉,因為我覺得我做錯了什么,但我不知道它是什么。

到目前為止,我在 Python 中運行以下代碼(使用 Jupyter 筆記本,如果有區別的話):

首先,我初始化了一個很長的(多級?)列表:

object = [[[[[[[[None for i in range(2)]  
               for j in range(2)] 
              for k in range(2)] 
             for l in range (2)] 
            for m in range (2)] 
           for n in range (2)]
          for o in range (2)]
         for p in range (2)]

接下來,我運行一堆循環,一個在另一個里面,然后運行一個 function(這取決於我在循環中使用的所有索引),將結果分配給我在上面創建的一個位置:

for i in range(2):
    for j in range(2):
        for k in range(2):
            for l in range(2):
                for m in range(2):
                    for n in range(2):
                        for o in range(2):
                            for p in range(2):
                                object[i][j][k][l][m][n][o][p] = function(i,j,k,l,m,n,o,p) 

以下是兩個相關的問題:

  1. function 在每次迭代中返回的對象彼此完全獨立(例如,我可以在一台計算機上運行循環的每次迭代並稍后收集它們)。 所以我想這個循環將是在並行/多處理中解決的理想候選者。 如果是這樣,我該怎么做? 我發現一些提到並行運行嵌套循環,但我不明白它如何適用於我的案例。 完全披露:我從未在 Python 中並行運行任何東西。

  2. 這個列表(引用這個相當不愉快的object[i][j][k][l][m][n][o][p] )你將如何正確保留結果(以你可以找到的方式之后)? 或者你能建議一個更好的方法嗎? 如果相關,則 function 返回的對象具有 pandas 數據幀、數字和字符串等屬性。

對於您的第一個問題,我建議您在此處查看最佳答案,以了解如何並行化我在下面概述的 for 循環(它回答了問題 2):

如何並行化一個簡單的 Python 循環?

第二個問題:

#dummy function for illustrative purposes
def function(a,b,c,d,e,f,g,h):
  return a+b+c+d+e+f+g+h

如果函數的 output 是可散列的,我將創建一個字典:

#This is your 'objects'
O={}

for y in range(2**8):
    #this generates all the permutations you were after I believe
    s=format(y, '#010b')[2:]
    #print(s) #uncomment to see what it does
    #This is slightly messy, in that you have to split up your integer into its components, but I've seen worse.
    O[y]=function(int(s[0]),int(s[1]),int(s[2]),int(s[3]),int(s[4]),int(s[5]),int(s[6]),int(s[7]))

#Now, if you wanted to print the output of f(1,1,1,1,1,1,1,1):
g='11111111'
print(O[int(g,2)]) #uncomment to see what it does 

#print(O) #uncomment to see what it does 

如果 output 不可散列,則保留為列表:

O=[] 

for y in range(2**8):
    #this generates all the permutations you were after I believe
    s=format(y, '#010b')[2:]
    #print(s) #uncomment to see what it does
    #This is slightly messy, in that you have to split up your integer into its components, but I've seen worse.
    O.append(function(int(s[0]),int(s[1]),int(s[2]),int(s[3]),int(s[4]),int(s[5]),int(s[6]),int(s[7])))

#Now, if you wanted to print the output of f(1,1,1,1,1,1,1,1):
g='11111111'
#print(O[int(g,2)]) #uncomment to see what it does 

#print(O) #uncomment to see what it does 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM