ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sun, 30 Jun 2013 17:03:15 +0200refresh numpy array in a for-cyclehttps://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 19:36:41 +0200https://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>
https://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 17:03:15 +0200https://ask.sagemath.org/question/10291/refresh-numpy-array-in-a-for-cycle/?answer=15164#post-id-15164