I am trying to modify a list while in a loop.
Lets assume that we have a class called Node with 3 properties (Node.x, Node.y, Node.z). There are two lists filled with N and M occasions of the object Node.
I am trying to have bilateral matches/connections between two lists so after each pairing the initial objects has to be modified in order to continue with comparing the other pairs.
This is a sample code described above.
offer = [ Node_o1, Node_o2, ...., Node_oN ]
demand = [ Node_d1, Node_d2,...., Node_dM ]
connections = []
disThresh = 100
for i in offer:
for j in demand:
dist = Distance(i,j)
if dist < disThresh and min(i.z, j.z) > 0: #if there is z available to send
print 'Connected offer %r with demand %r. Dist: %r' % (i , j, dist)
link = min(i.z, j.z)
i.z = i.z - link
j.z = j.z - link
connections.append([i,j])
After the half of the iterations the program behaves very strangely, because apparently it uses the initial data from the iterator and not the modified. I have tried to iterate on a copy of the list (offer[:]
) but still it does not work. While loops or enumerators (for i,v in enumerate(offer):
) do not work either.
Could you propose an elegant working approach to this problem? Thank you in advance.