[英]"TypeError: <lambda>() takes 1 positional argument but 2 were given" using reduce()
I want to return sum of square of numbers passed in list.我想返回列表中传递的数字的平方和。
from functools import reduce
def square_sum(numbers):
return reduce(lambda x: x ** 2, numbers)
print(square_sum([1, 2, 2]))
However i am getting the error: TypeError: <lambda>() takes 1 positional argument but 2 were given
.但是我收到错误: TypeError: <lambda>() takes 1 positional argument but 2 were given
。 I couldn't understand reason behind it.我无法理解其背后的原因。
Here's how you might define sum
if it didn't exist:如果sum
不存在,您可以这样定义它:
from functools import reduce
def sum(it):
return reduce(lambda acc, val:acc + val, it)
Or:或者:
from functools import reduce
import operator
def sum(it):
return reduce(operator.add, it, 0)
functools.reduce
reduces the values produced by an iterator to a single value by repeatedly combining consecutive values using the function you provide. functools.reduce
通过使用您提供的 function 重复组合连续值,将迭代器生成的值减少为单个值。 So the function needs to be able to combine two values and therefore must take two arguments.因此 function 需要能够组合两个值,因此必须采用两个 arguments。
So you could define sum_of_squares
using reduce
, like this, although there are a lot of corner cases to cope with:因此,您可以像这样使用reduce
定义sum_of_squares
,尽管有很多极端情况需要处理:
from functools import reduce
def sum_of_squares(it):
it = iter(it)
try:
first = next(it)
except StopIteration:
return 0
return reduce(lambda acc, val: acc + val * val,
it,
first * first)
Personally, I think the following is clearer:就个人而言,我认为以下内容更清楚:
def sum_of_squares(it):
return sum(map(lambda x:x ** 2, it))
The function
parameter to reduce()
should take two arguments: an old one and a new one. reduce()
的function
参数应该采用两个 arguments:一个旧的和一个新的。 To sum, you'd just need to add them together:总而言之,您只需要将它们加在一起:
lambda r, x: x**2 + r
However, that doesn't actually do what you want because the first element never gets squared (so it doesn't get the right answer if the first element is >1).然而,这实际上并没有做你想做的,因为第一个元素永远不会被平方(所以如果第一个元素>1,它就得不到正确的答案)。 You might be thinking reduce()
is like sum ( map ())
:你可能认为reduce()
就像sum ( map ())
:
def square_sum(numbers):
return sum(map(lambda x: x**2, numbers))
But it's more readable to replace the map
with a generator expression:但是用生成器表达式替换map
更具可读性:
def square_sum(numbers):
return sum(x**2 for x in numbers)
print(square_sum([1, 2, 2])) # -> 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.