python减少错误?
以下是我的 python 代码:
>>> 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 <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)
>>>
我该如何修复它? 谢谢!
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 <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)
>>>
How can I fix it?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的 lambda 仅接受一个参数,但
reduce
需要一个接受两个参数的函数。让你的 lambda 接受两个参数。由于您没有说出您希望这段代码做什么,我只是猜测:
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:
你的问题本身有点不清楚。不管怎样,我只是假设——
我假设你可能有兴趣获得列表中所有元素的总和。如果这是问题所在,那么可以分两步解决:
1)第一步应该是压平列表。
2)然后添加列表的所有元素。
一个衬垫
另一个假设,如果您的问题是逐项减去列表中元组的每个元素,则使用此:
如果问题是其他问题,请详细说明。
PS:Python 列表理解比其他任何东西都更好、更高效。
Your problem itself is a bit unclear. Anyway, i have taken just assumption--
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.
One liner
Another assumption, if your problem is to minus every element of tuple by item in the list then use this:
If the problem is something else then please elaborate.
PS: Python List comprehension is far better and efficient than anything else.
reduce
期望给定的函数接受 2 个参数。对于可迭代中的每个项目,它将向函数传递当前项目以及函数的前一个返回值。因此,获取列表的总和是reduce(lambda: x,y: x+y, l, 0)
如果我理解正确,要获得您想要获得的行为,请更改代码to:
但我可能误解了你想要得到的东西。
更多信息位于
reduce
函数的文档字符串中。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 isreduce(lambda: x,y: x+y, l, 0)
If I understand correctly, to get the behavior you were trying to get, change the code to:
But I might be mistaken as to what you were trying to get.
Further information is in the
reduce
function's docstring.