Your function takes 2 iterables and counts the number of times, by index, the number from one iterable is greater than the other. It then does the same operation with lists in the opposite order.
It’s far easier to show an example:
def solve(a, b):
return map(lambda t: sum([x > y for x, y in zip(*t)]), ((a, b), (b, a)))
L1 = [1, 2, 3, 1]
L2 = [4, 5, 1, 5]
res = list(solve(L1, L2)) # [1, 3]
sum with bool
res[0] = 1
because 1 < 4, 2 < 5, 3 > 1, 1 < 5.
res[1] = 3
because 4 > 1, 5 > 2, 1 < 3, 5 > 1.
Note that sum
with an iterable of Boolean values consider True
as 1
and False
as 0
. This is natural because bool
is implemented as a subclass of int
. The bold values above are considered True
and therefore a count of such instances will be the result of a sum
over those values.
list comprehension
A list comprehension is easier to comprehend:
res = [sum(i > j for i, j in zip(*L)) for L in ((L1, L2), (L2, L1))]
generator expression
In fact, since map
returns a lazy iterator, solve
more closely resembles a generator expression, which should perform better than the map
variant:
res = (sum(i > j for i, j in zip(*L)) for L in ((L1, L2), (L2, L1)))
You can then iterate the generator expression:
for item in res:
print(item)
Or exhaust the generator via a function such as list
:
res_list = list(res)
2
solved Understanding function with map / lambda / sum / zip [closed]