I have a Python function which takes a parameter and returns 2 outputs. I want to call this for all the elements in a list and combine the return values for each invocation as below:
a1, b1 = func(p[0])
a2, b2 = func(p[1])
a3, b3 = func(p[3])
a = a1 & a2 & a3
b = b1 + b2 + b3
How can I refactor this to a one liner using the += , &= and the reduce operators in Python?
Thanks
We can decompose this problem into individual tasks:
func across the elements p[0], p[1], ... of an iterable/sequence p is map(func, p).
(a1, b1), (a2, b2) so the assignment does not need special handling.a1 & a2 & ... for a sequence/iterable a is reduce(lambda new, total: new & total) and likewise for +.
(a1, b1), ... instead of a pair of streams a1, ... and b1, ... we must operate on both at once.a, b = result.from functools import reduce
def func(a): return a, a
p = range(1, 5, 2)
def reduction(new, total):
return new[0] & total[0], new[1] + total[1]
mapped = map(func, p)
reduced = reduce(reduction, mapped)
a, b = reduced
If desired, this can be written in one statement/line.
>>> a, b = reduce(lambda new, total: (new[0] & total[0], new[1] + total[1]), map(func, p))
>>> a
1
>>> b
4