The following line doesn't seem to work:
(count, total) += self._GetNumberOfNonZeroActions((state[0] + x, state[1] - ring, state[2]))
I guess it is not possible to use the += operator in this case. I wonder why?
edit: Actually what I want is to add to variables count and total the values given by the tuple returned by that function. Now that I think of it, it doesn't make sense to allow (a, b) += (1, 2), as it would be creating a new tuple, right?
In other words, s there a way to simplify this?
res = self._GetNumberOfNonZeroAction开发者_运维技巧s((state[0] + x, state[1] + ring, state[2]))
count, total = res[0], res[1]
Your observation is right: a += b
for any a and b means the same as a = a + b
(except that it may save one evaluation of a). So if a
is a tuple, the only thing that can be +=
'd to it is another tuple; if a
is a temporary unnamed tuple, that +=
will of course be unobservable -- Python helps you out by catching that special case as a syntax error. You need to give the tuple a name (or other reassignable reference) before you += to it...:
>>> thetup = (a, b)
>>> thetup += (1, 2)
>>> thetup
(23, 45, 1, 2)
if the syntax (a, b) += (1, 2)
was accepted, it would of course have to imply the same functionality... but without any possible observable way to check that the appending had actually occurred, which really makes just about no sense. Good thing the syntax is NOT accepted, therefore!-)
You are mixing two concepts together. Python supports tuple unpacking which allows you to assign more that one variable in a single line.
The +=
operator gets expanded by the interpreter since it is only a shorthand. Your example ((a, b) += (1, 2)
) would be expanded to this:
(a, b) = (a, b) + (1, 2)
which, when you look at it, doesn't make a whole lot of sense. Just remember that tuple unpacking only works for the assignment of values to variables.
If you want to work on numeric arrays, I recommend using numpy http://numpy.scipy.org/.
It allows you to do this:
>>> from numpy import *
>>> count_total = array((0,0))
>>> count_total += (1,2)
>>> count_total
array([1, 2])
精彩评论