I'm currently trying to write a function that will give me a tuple whose 0 index is the amount of lines in that file, and whose 1 index is how many characters are in that file. So far, I have a list of tuples, which looks like this:
mapped = [(1, 50), (1, 11), (1, 58)]
The line I'm trying to write is this:
reduce(lambda x:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
If it works correctly, then it should return a tuple of (3, 119). However, I'm getting an error of
TypeError: reduce() of empty sequence with no initial value
Can anybody figure out why this is?
Nobody answer why there is an error:
TypeError: reduce() of empty sequence with no initial value
When the list literal which is second parameter is empty, the error occurs. So if you try
reduce(lambda x, y:(x[0]+y[0], x[1]+y[1]), [])
You'll get the error.
map(sum, ...)
fits better, looks beautiful.
map(sum, zip(*mapped))
You can use itertools.izip_longest
if lengths of the lists are different.
Use this way:
>>> reduce(lambda x,y:(x[0]+y[0], x[1]+y[1]),[i for i in mapped])
(3, 119)
>>> reduce(lambda x,y:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
(3, 119)
What you miss is that lambda
should take two parameters, you just give one.
For Python3.x see the code below:
>>> from functools import reduce
>>> reduce(lambda x:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 positional argument (2 given)
>>> reduce(lambda x,y:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
(3, 119)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With