11 Feb 21:56
Want to eliminate direct for-loop
Dinesh B Vadhia <dineshbvadhia <at> hotmail.com>
2012-02-11 20:56:51 GMT
2012-02-11 20:56:51 GMT
Could the following be written
without the direct for-loop?
import numpy
# numpy vector r of any data type and length, eg.
# 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]
# 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 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]
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
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!
_______________________________________________ NumPy-Discussion mailing list NumPy-Discussion <at> scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion
RSS Feed