ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sun, 30 Jun 2013 10:03:15 -0500refresh numpy array in a for-cyclehttp://ask.sagemath.org/question/10291/refresh-numpy-array-in-a-for-cycle/Hi experts!
Im writing a code with a numpy array L, the numpy matrix M and the next script:
for x in L:
for l in srange(N):
z= l in L
if z is False and M[x,l] != 0:
L=np.append(L,l)
here, in the end of the cycle, new elements are incorporated to the array 'L'.
I want these new elements be considered as 'x' index in the cycle.
When I execute the script I see that only the 'originals' elements of L are considered as 'x'.
How can i fix it?
Waiting for your answers.
Thanks a lot!
Wed, 26 Jun 2013 12:36:41 -0500http://ask.sagemath.org/question/10291/refresh-numpy-array-in-a-for-cycle/Answer by vdelecroix for <p>Hi experts!</p>
<p>Im writing a code with a numpy array L, the numpy matrix M and the next script:</p>
<pre><code>for x in L:
for l in srange(N):
z= l in L
if z is False and M[x,l] != 0:
L=np.append(L,l)
</code></pre>
<p>here, in the end of the cycle, new elements are incorporated to the array 'L'.</p>
<p>I want these new elements be considered as 'x' index in the cycle.</p>
<p>When I execute the script I see that only the 'originals' elements of L are considered as 'x'.</p>
<p>How can i fix it?</p>
<p>Waiting for your answers.</p>
<p>Thanks a lot!</p>
http://ask.sagemath.org/question/10291/refresh-numpy-array-in-a-for-cycle/?answer=15164#post-id-15164You may use a while loop instead. It is never sane to modify the list you iterate on inside a for loop.
i = 0
while i < len(L):
x = L[i]
for l in srange(N):
if not (l in L) and M[x,l] != 0:
L = np.append(L,l)
Comment: the test "l in L" might be expensive (if the answer is False then you have to look through the whole list).Sun, 30 Jun 2013 10:03:15 -0500http://ask.sagemath.org/question/10291/refresh-numpy-array-in-a-for-cycle/?answer=15164#post-id-15164