使用Python中的并行计算加速嵌套循环

时间:2017-12-21 18:25:13

标签: python python-3.x loops parallel-processing

我在代码中包含以下代码:

import pandas as pd
import itertools

# I create all combinations of triples from the set of numbers 1,2, ..., 7
a1 = list(map(list, itertools.product([0,1,2,3,4,5,6,7], repeat=3)))
# Output:
# [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 0, 4]...e.t.c.

# I'm deleting sub-lists with repeating values      
aa=[]
for i in range(len(a1)):
    if len(list(set(a1[i])))==3:
        x = a1[i]
        aa.append(x)        
# Output:
# [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 1, 5]...e.t.c. 

# I create a list of value representation from the 'aa' list      
aa_representation=[]
for i in range(len(aa)):
    y =''.join(map(str, ['b' if x%2 else 'a' for x in aa[i]]))
    aa_representation.append(y)    
# Output:
# ['aba', 'abb', 'aba', 'abb',..., 'bab']

# I create lists from values from 'aa' matching to the representations from the 'aa_representation' list
aaa=[]
aab=[]
aba=[]
baa=[]
abb=[]
bba=[]
bab=[]
bbb=[]
for i in range(len(aa_representation)):
    if aa_representation[i]=='aaa':
        aaa.append(aa[i])
    if aa_representation[i]=='aab':
        aab.append(aa[i])
    if aa_representation[i]=='aba':
        aba.append(aa[i])
    if aa_representation[i]=='baa':
        baa.append(aa[i])
    if aa_representation[i]=='abb':
        abb.append(aa[i])
    if aa_representation[i]=='bba':
        bba.append(aa[i])
    if aa_representation[i]=='bab':
        bab.append(aa[i])
    if aa_representation[i]=='bbb':
        bbb.append(aa[i])

# I create a list with sub-lists containing after each one value of a given representation
combinations=[]
for q in range(len(aaa)):
    for w in range(len(aab)):
        for e in range(len(aba)):
                for r in range(len(abb)):
                    for t in range(len(bbb)):
                                x = [aaa[q],aab[w],aba[e],abb[r],bbb[t]]
                                if 'something that reduces the number of matching combinations':
                                    combinations.append(x)

我怎样才能加快代码的执行速度?因为现在它和连枷的构造一样粗糙:)我可以在这里使用一些并行计算吗? Cython暂时不可能,因为我与他没有任何联系。我将非常感谢任何评论。

0 个答案:

没有答案