Reputation: 16701
I have a class with multiple vectors from measurements. I need to iterate over these vectors but would like to use only chosen measurements. The simplified version of what I build so far is below:
import pylab as pl
class IterationReturn(object):
def __init__(self):
self.a = (1,2,3,4,5,6,7,8,9)
self.b = (10,20,30,40,50,60,70,80,90)
self.c = (-1,-2,-3,-4,-5,-6,-7,-8,-9)
self.i = 0
def returnNextSet(self):
self.aIter = self.a[self.i]
self.bIter = self.b[self.i]
self.cIter = self.c[self.i]
self.i +=1
return (self.aIter, self.bIter, self.cIter)
if __name__ == '__main__':
iteration = IterationReturn()
for i in range(len(iteration.a)):
# x takes aIter value from iteration.returnNextSet()
# y takes bIter value from iteration.returnNextSet()
x,y = iteration.returnNextSet()
pl.scatter(x, y)
pl.show()
I don't want to use x,y,z = iteration.returnNextSet()
which would work in this example, but in practice I have many more values and do not want to assign them all. I can't find a way to assign only to aIter
and bIter
.
I have an error:
x,y = iteration.returnNextSet()
ValueError: too many values to unpack
In my problem I have many measurements (a,b, ... ,z) and for example I want to assign x=d and y=k I also think it should be done in different way from the beginning like designing new class with inheritance but not sure how to do that. Would appreciate your help
Upvotes: 0
Views: 91
Reputation: 184405
Just do:
results = iteration.returnNextSet()
Then refer to the values as results[0]
, results[1]
, and so on. You can do len(results)
to see how many you got.
Upvotes: 1
Reputation: 375865
The best way to do this is to return a dictionary:
return {'a': self.aIter, 'b':self.bIter, 'c': self.cIter, ...}
Then you can assign:
NS = iteration.returnNextSet()
x, y = NS['x'], NS['y']
.
Keeping your current function, you could assign the first two values:
x, y = iteration.returnNextSet()[:2]
and in Python 3 you will be able to assign the rest of the values to another tuple:
x, y, *args = iteration.returnNextSet()
Upvotes: 1
Reputation: 142236
Not quite sure why you'd want to do this, but here's one way:
class Test(object):
def __init__(self):
self.a = (1,2,3,4,5,6,7,8,9)
self.b = (10,20,30,40,50,60,70,80,90)
self.c = (-1,-2,-3,-4,-5,-6,-7,-8,-9)
def iter_over(self, *args):
items = [getattr(self, arg) for arg in args]
return zip(*items)
t = Test()
for a, c in t.iter_over('a', 'c'):
print a, c
1 -1
2 -2
3 -3
4 -4
5 -5
6 -6
7 -7
8 -8
9 -9
Or:
for items in t.iter_over('c', 'b', 'a'):
print items[1] # will be b (or 2nd passed above) etc...
Upvotes: 1