Home > Mobile >  Optimizing .append nested loops
Optimizing .append nested loops

Time:01-20

Is there a more elegant (and fast) way to do something like this :

Seg = []

for i in components :
    Segg = []
    
    for j in i :

        Segg.append(np.array(points)[j]) 
    Seg.append(Segg)

I'm not very familiar with nested loops, even less when we must .append something twice.

EDIT : points is a 3-d array and components provided from networkx as a generator of sets of nodes, one for each component of a graph G.

CodePudding user response:

The fastest way that yields the same results is:

parray = np.array(points)
Seg = [[parray[j] for j in i] for i in components]

Comprehensions are the fastest and most efficient way of creating lists. Appending in loops isn't efficient.

  •  Tags:  
  • Related