Reputation: 2951
I'm trying to make kind of pre-defined rules for incrementing some variables. I'm trying to do this by making a dictionary where the rule is linked to some key. Then, in the loop, I reference the key. I thought that it would be equivalent to setting:
i = i+1
to say
i=Coord['DR'][0]
But that's not what I'm finding. Here is a script that replicates the error:
i =0
j =0
LL = 0
Coord ={
'DR':[i+1,j+1]
}
while LL <=10:
Choice = 'DR'
print i,j
i = Coord[Choice][0]
j = Coord[Choice][1]
LL +=1
the current output:
0 0
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
I want:
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
Upvotes: 0
Views: 93
Reputation: 123473
You could use an object-oriented approach and defineRule
objects. For this particular case you could use the indexing operator and make it have the side-effect of incrementing the proper variable.
i = 0
j = 0
class Rule1(object):
def __getitem__(self, index):
if index == 0:
return i+1
elif index == 1:
return j+1
else:
raise IndexError()
Coord = {'DR': Rule1()}
LL = 0
while LL <= 10:
Choice = 'DR'
print i, j
i = Coord[Choice][0]
j = Coord[Choice][1]
LL += 1
The one in the example is so simple and didn't even need an__init__()
constructor, but others could, which would allow for some fairly sophisticatedRule
-type classes to be defined and used, plus they would facilitate code-reuse — for example you could add constructors to them to specify specific values that affected what they did, effectively parameterizing them.
Upvotes: 1
Reputation: 365797
When you do this:
Coord ={
'DR':[i+1,j+1]
}
That just evaluates i+1
and j+1
and stores the resulting values—1
and 1
—in Coord['DR']
.
The fact that you later reassign i
to some other value than 0
doesn't mean that the number 1
suddenly changes into a different number. If you could do that, you could break the universe.
There are two reasons you could be confused about this.
You might expect Python to store expressions that are lazily evaluated on demand. It doesn't. It stores values. If you want an expression that's lazily evaluated on demand, you need to do that explicitly, with a function.
Alternatively, you might expect Python to store references to variables. It doesn't. It stores references to values. This one, you can't even do explicitly. Variables aren't real "things", they're just names for values. When you reassign i
to some other value, like i = i + 1
, that's just saying that i
is now a name for 1
instead of a name for 0
.
Upvotes: 3
Reputation: 198368
After the initial six lines, Coord['DR']
will be [1, 1]
(because i + 1
is 0 + 1
, which is 1
; similar for j
). You want something that can calculate for you... A function! Or a lambda!
i =0
j =0
LL = 0
Coord ={
'DR':[lambda i: i + 1, lambda j: j + 1]
}
while LL <=10:
Choice = 'DR'
print i,j
i = Coord[Choice][0](i)
j = Coord[Choice][1](j)
LL +=1
Upvotes: 3