[Numpy-discussion] Want to eliminate direct for-loop
Dinesh B Vadhia
dineshbvadhia at hotmail.com
Sat Feb 11 15:56:51 EST 2012
Could the following be written without the direct for-loop?
import numpy
# numpy vector r of any data type and length, eg.
r = numpy.ones(25, dtype='int')
# s is a list of values (of any data type), eg.
s = [47, 27, 67]
# c is a list of (variable length) lists where the sub-list elements are index values of r and len(s) = len(c), eg.
c = [[3, 6, 9], [6, 11, 19, 24], [4, 9, 11, 21 ]]
# for each element in each sub-list c, add corresponding s value to the index value in r, eg.
for i, j in enumerate(c):
r[j] += s[i]
So, we get:
r[[3, 6, 9]] += s[0] = 1 + 47 = 48
r[[6, 11, 19, 24]] += s[1] = 1 + 27 = 28
r[[4, 9, 11, 21]] += s[2] = 1 + 67 = 68
ie. r = array([ 1, 1, 1, 95, 68, 1, 122, 1, 1, 162, 1, 95, 1, 1, 1, 1, 1, 1, 1, 28, 1, 68, 1, 1, 28])
Thank-you!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20120211/2462097b/attachment.html>
More information about the NumPy-Discussion
mailing list