196 | def mapzip(func, a, b): |
197 | """ |
198 | Applies a function over the zip of iterables a and b, |
199 | giving back an object of the same type as a. That is, |
200 | c[i] = func(a[i], b[i]). |
201 | |
202 | Warning: this is not meant to be applied to a tensor --it will not work |
203 | |
204 | For example: |
205 | |
206 | ``` |
207 | from collections import namedtuple |
208 | from operator import add |
209 | |
210 | coords = namedtuple("coordinates", ["x", "y"]) |
211 | |
212 | a = coords(1,2) |
213 | b = coords(2,3) |
214 | |
215 | c = mapzip(add, a, b) # coordinates(x=2, y=4) |
216 | |
217 | a = list(a) |
218 | b = list(b) |
219 | |
220 | c = mapzip(add, a, b) # [2, 4] |
221 | ``` |
222 | |
223 | Args: |
224 | func (callable): a function with two arguments |
225 | a (iterable; e.g., list or namedtuple) |
226 | b (iterable; e.g., list or namedtuple) |
227 | |
228 | Returns: |
229 | object of type(a) |
230 | |
231 | """ |
232 | lst = [func(x[0], x[1]) for x in zip(a, b)] |
233 | if is_namedtuple(a): |
234 | return type(a)(*lst) |
235 | return type(a)(lst) |