优化并加速Python中的循环

时间:2017-11-22 08:33:47

标签: python python-3.x

如何优化这三段代码? 特别是第三个,因为列表值之间有很多组合,1000个输入的时间危险地更长。

代码1:

e00=[]
for i in range(len(c1)):
    for j in range(len(d1[i])):
        if d1[i][j]%2==0:
           d = [c1[i],d1[i][j]]
           e00.append(d)

代码2:

sciezki=[]
for i in range(len(out2)):     
    x1 = out2[i][-len(out2[i])]
    x2 =out2[i][-1]    
    z1 = nx.shortest_path(g, x1, x2)  
    if z1 == out2[i] and len(z1)==8:
          sciezki.append(z1)

代码3:

out=[] 
for h in range(len(k)):
    if len(out)!=0:
       k2 = [out, k[h]]
       for q in range(len(k2[0])):
           for w in range(len(k2[1])):
               r = list(chain(k2[0][q],k2[1][w]))
               p = [n for n, _ in groupby(r)]
               if len(p)==h+2:
                  out.append(p)  
    else:
       for i in range(len(k[0])):
           for j in range(len(k[1])):
               r = list(chain(k[0][i],k[1][j]))
               p = [n for n, _ in groupby(r)]
               if len(p)==3:
                   out.append(p)

1 个答案:

答案 0 :(得分:1)

代码1

将条件列表推导与枚举一起使用:

e00 = [[c_val, d_val] 
       for i, c_val in enumerate(c1) 
       for d_val d1[i] 
       if not d_val % 2]

代码2

只需要稍作修改。

g = ...  # Undefined in sample code.
sciezki = []
for out2_val in out2:     
    x1 = out2_val[-len(out2_val)]
    x2 = out2_val[-1]    
    z1 = nx.shortest_path(g, x1, x2)  
    if z1 == out2_val and len(z1) == 8:
        sciezki.append(z1)
        x = '\n'.join(map(str,sciezki))  # Remove if possible.