Parallel arithmetic?

Robert Kern rkern at ucsd.edu
Fri Aug 5 01:11:05 CEST 2005


Terrance N. Phillip wrote:
> Given a and b, two equal length lists of integers, I want c to be 
> [a1-b1, a2-b2, ... , an-bn]. I can do something like:
> 
> c = [0] * len(a)
> for ndx, item in enumerate(a):
>      c[ndx] = item - b[ndx]
> 
> But I'm wondering if there's a better way, perhaps that avoids a loop?
> 
> Nick.
> 
> (I seem to recall from my distant past that this sort of thing was dead 
> easy with APL... c = a-b, more or less.)

If you're doing this kind of thing often, look into using Numeric.

http://numeric.scipy.org

In [21]: from Numeric import array

In [22]: a = array(range(10))

In [23]: b = array(range(10, 20))

In [24]: c = a - b

In [25]: c
Out[25]: [-10,-10,-10,-10,-10,-10,-10,-10,-10,-10,]

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list