Can't execute (a, b) + = (1, 2) in python?

The following line does not work:

(count, total) += self._GetNumberOfNonZeroActions((state[0] + x, state[1] - ring, state[2]))

I assume that in this case the + = operator cannot be used. I wonder why?

edit: Actually, I want to add to the number of variables and summarize the values ​​given by the tuple returned by this function. Now, when I think about it, it makes no sense to allow (a, b) + = (1, 2), since this will be creating a new tuple, right?

In other words, is there a way to simplify this?

    res = self._GetNumberOfNonZeroActions((state[0] + x, state[1] + ring, state[2]))
    count, total = res[0], res[1]
+3
source share
3 answers

If you want to work with numeric arrays, I recommend using numpy http://numpy.scipy.org/ .

This allows you to do this:

>>> from numpy import *
>>> count_total = array((0,0))
>>> count_total += (1,2)
>>> count_total
array([1, 2])
+1
source

: a += b a b , a = a + b ( , a). , a , , += 'd, - ; a , +=, , - Python , . ( ) , + = ...:

>>> thetup = (a, b)
>>> thetup += (1, 2)
>>> thetup
(23, 45, 1, 2)

(a, b) += (1, 2), , , ... - , , . , , ! -)

+10

You mix the two concepts together. Python supports tuple unpacking , which allows you to assign more than one variable on a single line.

The operator is +=expanded by the interpreter, since it is only abbreviated. Your example ( (a, b) += (1, 2)) will be expanded as follows:

(a, b) = (a, b) + (1, 2)

which, when you look at it, doesn't make much sense. Just remember that unpacking tuples only works for assigning values ​​to variables.

+5
source

Source: https://habr.com/ru/post/1725124/


All Articles