So now let's reduce (). This is actually the one I always hated the most, because, in addition to a few examples involving + or *, almost every time I see a reduce () call with a non-trivial function argument, I need to grab a pen and chart paper, which actually served in this function before I understand what the reduce () method should do. Therefore, in my opinion, the applicability of the reduce () method is largely limited by associative operators, and in all other cases it is better to write the accumulation cycle explicitly.
Quickly, what does the following code do?
total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
You can understand this, but it takes time to unravel the expression to figure out what is happening. Using short nested def statements makes things a little better:
def combine (a, b): return 0, a[1] + b[1] total = reduce(combine, items)[1]
But it would be best if I just used the for loop:
total = 0 for a, b in items: total += b
Or the sum () expression and the generator:
total = sum(b for a,b in items)
Many shorthand () functions are more readable when writing as for loops.