2one
2one

Reputation: 1085

Array operation in Python

How do I do the following in Python:

array_1 = [x1, x2, x3, x4, x5, x6, ....]
array_2 = [y1, y2, y3]

array_3 = [(x1-y1), (x2-y2), (x3-y3), (x4-y1), (x5-y2), (x6-y3)]

The number of elements in array_2 is always less than the number of elements in array_1.

array_1 and array_2 have an arbitrary number of elements.

[num of elements in array_1] mod [number of elements in array_2] = 0

Upvotes: 3

Views: 1018

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1124070

from itertools import izip, cycle

array_3 = [a - b for a, b in izip(array_1, cycle(array_2))]

which would accomodate arbitrary sizes for array_2.

Here itertools.izip() combines elements from both lists into pairs, and the itertools.cycle() utility will re-use the second list over and over again to provide something to pair with.

If you don't need a list as output, only need to iterate over the result, you could use itertools.imap() and operator.sub too:

from itertools import imap, cycle
import operator

for result in imap(operator.sub, array_1, cycle(array_2)):
    # do something with the result

For large input lists, this saves you having to store the intermediary results in yet another list.

Upvotes: 10

Abhijit
Abhijit

Reputation: 63767

Itertools has loads of tools to accommodate your problem

Understanding your problem

  1. One of the array is shorter than the other
  2. The Shorter array should be cycled until the longer array is exhausted
  3. Create a pair of the longer array and the cycled shorter array
  4. Subtract the elements within the pair

So here is the implementation

>>> arr1 = range(1,10)
>>> arr2 = range(20,23)
>>> from operator import sub
>>> from itertools import izip, cycle, starmap
>>> list(starmap(sub, izip(arr1, cycle(arr2))))
[-19, -19, -19, -16, -16, -16, -13, -13, -13]

Upvotes: 6

mgilson
mgilson

Reputation: 310097

You could use operator.sub with map:

array_3 = map(operator.sub,array_1,array_2+array_2)

Or, you could do it with zip:

array_3 = [x-y for x,y in zip(array_1,array2+array2)]

And you can get rid of the silly concatenation of array2 with itself using itertools.cycle

array_3 = [x-y for x,y in zip(array_1,cycle(array_2))]

Upvotes: 5

Related Questions