I’m new to Python’s iterators, so maybe my language is not always correct.
I have a class wrapping a list of numpy.ndarray:
class wrapper:
def __init__(self, myList):
self.myList = myList
def getArrayIterator(self):
for arr in self.myList:
yield arr
#set list of arrays in wrapper
myList = [rand(3,3), rand(3,3), rand(3,3)]
w = wrapper(myList)
As I understood it, the second method returns a generator.
Now I want to use that generator to loop over the list and reset the arrays to something else:
for a in w.getArrayIterator():
a = zeros((3,4))
I was hoping to have pass by reference semantics here, but that doesn’t seem to be the case.
So I tried using Python’s send() in my getArrayIterator function:
# ...
def getArrayIterator(self):
for arr in self.myList:
val = (yield arr)
if val is not None:
arr = val
# ...
But that wont work either because:
a.send(zeros((3,4)))
AttributeError: 'numpy.ndarray' object has no attribute 'send'
Is there a simple solution to achieve my desired behavior?
Am I missing something?
EDIT: It has been pointed out to me, that I should provide more Information about my actual problem. The example above is of course simplified.
I have a list of lists of numpy.ndarray representing a tensor T encapsulated in my class. When accessing an element of T: t_ijkl I need to multiply the matrices stored in the list: A(i)*B(j)*C(k)*D(l), first and last are row / col vectors.
So there is a set of A, a set of B, etc. Each of which belongs to a gridpoint in my application.
I now wanted to have an iterator over all gridpoints and iterators over the matrices associated with each gridpoint.
The first Idea that came to mind was to use iterators c++ style to read and write the matrices. But as agf pointed out below, this is not really a feasible approach. So I think I’ll use the different iterators just for read access and specialized setter methods to set new values for the matrices.
I’m assuming this is a simplified example, because with the class you have there seems to be no reason not to just use a normal list.
When you do
you’re pointing the name
nameat the object at the first index insomelist, then pointing the namenameat the object'other'. You’re not ever pointingsomelist[0]at'other'.So in addition to
send, you need to actually assign to the list: