问题描述
我想编写一个 python 函数,使用 +
运算符添加所有参数.未指定参数数量:
def my_func(*args):返回 arg1 + arg2 + arg3 + ...
我该怎么做?
最好的问候
只需使用 sum 内置函数
>>>def my_func(*args):...返回总和(参数)...>>>my_func(1,2,3,4)10>>>我不知道你为什么要避免求和,但是我们开始:
>>>def my_func(*args):... return reduce((lambda x, y: x + y), args)...>>>my_func(1,2,3,4)10>>>您还可以使用 operator 代替 lambda
.add.
编辑 2:
我看了你的 其他 问题,看来您的问题是使用 sum
作为 max
的 key
参数使用自定义类时.我回答了您的问题,并在我的回答中提供了一种使用带有 sum
的类的方法.
I'd like to write a python function which adds all its arguments, using +
operator. Number of arguments are not specified:
def my_func(*args):
return arg1 + arg2 + arg3 + ...
How do I do it?
Best Regards
Just use the sum built-in function
>>> def my_func(*args):
... return sum(args)
...
>>> my_func(1,2,3,4)
10
>>>
Edit:
I don't know why you want to avoid sum, but here we go:
>>> def my_func(*args):
... return reduce((lambda x, y: x + y), args)
...
>>> my_func(1,2,3,4)
10
>>>
Instead of the lambda
you could also use operator.add.
Edit2:
I had a look at your other questions, and it seems your problem is using sum
as the key
parameter for max
when using a custom class. I answered your question and provided a way to use your class with sum
in my answer.
这篇关于如何编写一个添加所有参数的python函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!