in Python how to increment the values in a list without having to write a for
loop, e.g.:
group = [0]*3
item = [1,2,3]
group += item
print group
to get group = [1,2,3]
instead of group = [0,0,0,1,2,3]
?
in Python how to increment the values in a list without having to write a for
loop, e.g.:
group = [0]*3
item = [1,2,3]
group += item
print group
to get group = [1,2,3]
instead of group = [0,0,0,1,2,3]
?
You could use numpy module. This won't need a for
loop.
>>> import numpy as np
>>> group = np.array([0]*3)
>>> item = np.array([1,2,3])
>>> group += item
>>> group
array([1, 2, 3])
>>> list(group)
[1, 2, 3]
You can do element-wise operations (addition in this case) by using zip
within a list comprehension.
>>> group = [0]*3
>>> item = [1,2,3]
>>> group = [i + j for i,j in zip(group, item)]
>>> group
[1, 2, 3]
This is a general solution if group
didn't start out as all zeroes, and you wanted to add the current values with some new values.