[SciPy-User] At.: question about refresh numpy array in a for-cycle

Robert Kern robert.kern@gmail....
Tue Jul 2 03:42:58 CDT 2013


On Thu, Jun 27, 2013 at 12:00 AM, Josè Luis Mietta <
joseluismietta@yahoo.com.ar> wrote:
>
> 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?

There are a couple of things going on here. First, "for x in L:" always
iterates over the object initially assigned to the name "L". If that name
gets reassigned to a different object during the course of the loop, it
won't change the iteration. That's just how Python works.

Second, if you can modify the object in-place in the loop, that will affect
the iteration, but this is usually a bad idea. It becomes very hard to
reason about what is going to happen, and you will usually get it wrong.
np.append() cannot modify its array argument in-place. numpy arrays are
generally of a fixed size throughout their lifetime for various reasons.
That's why you had to reassign the result of np.append() back to the name
L. You need to use a Python list or some other extendable object in order
to modify the iteration in-place. Generally, np.append() is a sign that you
need to use some other data structure.


from collections import deque

# Convert to a list object that is efficient for appending.
# We will accumulate results in this list.
L = list(L)
# Make a First-In-First-Out queue out of the items.
# We will pull work items from this queue.
queue = deque(L)

while queue:
    x = queue.popleft()
    for l in srange(N):
        if l not in L and M[x,l] != 0:
            # Add it to the results.
            L.append(l)
            # And to the work queue for further processing.
            queue.append(l)

# I guess we need this back as an array again.
L = np.array(L)

--
Robert Kern
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20130702/3072bddd/attachment-0001.html 


More information about the SciPy-User mailing list