开发者

python reduce error?

The following is my python code:

>>> item = 1
>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> sums=reduce(lambda x:abs(item-x[1]),a)
Traceback (most recent call last):
  File "<stdin>", line 1, in &l开发者_开发百科t;module>
TypeError: <lambda>() takes exactly 1 argument (2 given)
>>> 

How can I fix it? Thanks!


Your lambda takes only one argument, but reduce requires a function that takes two arguments. Make your lambda take two arguments.

Since you didn't say what you want this code to do, I'll just guess:

the_sum=reduce(lambda x,y:abs(y[1]-x[1]),a)


Your problem itself is a bit unclear. Anyway, i have taken just assumption--

>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> a
[(1, 2, 3), (7, 2, 4)] # list of tuples

I am assuming that you might be interested in getting the sum of all the elements in the list. If that is the problem then that could be solved in 2 steps

1) The first step should be to flatten the list.

2) And then add all the elements of the list.

>>> new_list = [y for x in a for y in x] # List comprehension used to flatten the list
[1, 2, 3, 7, 2, 4] 
>>> sum(new_list)
19

One liner

>>> sum([y for x in a for y in x])
19

Another assumption, if your problem is to minus every element of tuple by item in the list then use this:

>>> [tuple(map(lambda y: abs(item - y), x)) for x in a]
[(0, 1, 2), (6, 1, 3)] # map function always returns a list so i have used tuple function to convert it into tuple.

If the problem is something else then please elaborate.

PS: Python List comprehension is far better and efficient than anything else.


reduce expects the function it is given to accept 2 arguments. For every item in the iterable it will pass the function the current item, and the previous return value from the function. So, getting the sum of a list is reduce(lambda: x,y: x+y, l, 0)

If I understand correctly, to get the behavior you were trying to get, change the code to:

a_sum = reduce(lambda x,y: x + abs(item-y[1]), a, 0)

But I might be mistaken as to what you were trying to get. Further information is in the reduce function's docstring.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜