如何编写一个添加所有参数的python函数? [英] How to write a python function that adds all arguments?

查看:25
本文介绍了如何编写一个添加所有参数的python函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 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 作为 maxkey 参数使用自定义类时.我回答了您的问题,并在我的回答中提供了一种使用带有 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函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆