Array work in Python

How to 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 is array_2

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

+3


source to share


3 answers


Itertools has many tools to solve your problem.

Understanding your problem



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]

      

+6


source


from itertools import izip, cycle

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

      

which will accommodate arbitrary sizes for array_2.

Here, it itertools.izip()

pairs items from both lists, and the itertools.cycle()

utility
will reuse the second list over and over again to provide something to combine with.



If you don't want the list as output, you only need to iterate over the result, you can use itertools.imap()

and operator.sub

:

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 lists of inputs, this saves you the trouble of storing intermediate results in another list.

+10


source


You can use operator.sub

with map

:

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

      

Or you can 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 array2 concatenation with itertools.cycle

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

      

+5


source







All Articles