Since you want a one-liner, something like this should help you:
a,b = int(all(ele == list(zip(*map(func,p)))[0][0] for ele in list(zip(*map(func,p)))[0])),sum(list(zip(*map(func,p)))[-1])
Breakdown:
The map
function applies a function to an iterable.
list(map(func,p))
Prints:
[(1, 3), (2, 4), (3, 5)]
This:
list(zip([(1, 3), (2, 4), (3, 5)]))
Prints:
[((1, 3),), ((2, 4),), ((3, 5),)]
Adding an *
before map
would transpose the list
:
list(zip(*map(func,p)))
Prints:
[(1, 2, 3), (3, 4, 5)]
The all
function is combined with a simple list comprehension in order to find if all elements of sublist 1 are equal. Here is a simpler version of it:
all(ele == lst[0] for ele in lst)
The same has been applied in this case like this:
all(ele == list(zip(*map(func,p)))[0][0] for ele in list(zip(*map(func,p)))[0])
Prints:
False
In order to convert True
/False
to 1
/0
, I have used the int()
function:
int(all(ele == list(zip(*map(func,p)))[0][0] for ele in list(zip(*map(func,p)))[0]))
Prints:
0
The second part of it, which is this: sum(list(zip(*map(func,p)))[-1])
calculates the sum of the second sublist.
sum(list(zip(*map(func,p)))[-1])
Prints:
12
Here is the full code:
def func(a):
return a,a+2
p = [1,2,3]
a,b = all(ele == list(zip(*map(func,p)))[0][0] for ele in list(zip(*map(func,p)))[0])),sum(list(zip(*map(func,p)))[-1])
print(a,b)
Output:
(0, 12)