Multiple increment operators on the same line Python

心已入冬 提交于 2019-12-10 13:55:20

问题


Is it possible to do multiple variable increments on the same line in Python?

Example:

value1, value2, value3 = 0
value4 = 100
value1, value2, value3 += value4

In my real program I have LOTS of variables that are different but must all be added on with a single variable at one point.

What I am currently doing that I wanted this to replace:

value1 += value4
value2 += value4
value3 += value4
...
value25 += value4

回答1:


You can create special function for it:

def inc(value, *args):
    for i in args:
        yield i+value

And use it:

value1 = value2 = value3 = 0
value4 = 100
value1, value2, value3 = inc(value4, value1, value2, value3)



回答2:


Tuple and generator unpacking can be useful here:

value1, value2, value3 = 0, 0, 0
value4 = 100
value1, value2, value3 = (value4 + x for x in (value1, value2, value3))



回答3:


You can update the variables through the dictionary of the current namespace (e.g. vars()):

>>> value1 = value2 = value3 = 0
>>> value4 = 100
>>> for varname in ("value1", "value2", "value3"):
...     vars()[varname] += value4
... 
>>> value1, value2, value3
(100, 100, 100)



回答4:


There is an easy way by making a list and looping over it:

value1, value2, value3 = 0
value4 = 100
valuelist = [value1, value2, value3]
for x in valuelist:
    x += value4


来源:https://stackoverflow.com/questions/34693927/multiple-increment-operators-on-the-same-line-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!