如何编写Python的功能,增加了所有的参数? [英] How to write a python function that adds all arguments?

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

问题描述

我想写一个Python功能,增加了它的所有参数,使用 + 运营商。未指定数量的参数:

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 + ...

我该怎么办呢?

此致

推荐答案

只需使用总和的建-in功能

Just use the sum built-in function

>>> def my_func(*args):
...     return sum(args)
...
>>> my_func(1,2,3,4)
10
>>>


编辑:

我不知道为什么你想避免相加,而是在这里我们去

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
>>>

而不是的λ你也可以使用的operator.add

EDIT2:

我看看你的<一个href=\"http://stackoverflow.com/questions/11519787/how-to-find-the-list-in-a-list-of-lists-whose-sum-of-elements-is-the-greatest\">other <一href=\"http://stackoverflow.com/questions/11520087/how-to-use-a-custom-function-in-maxx-key-custom-function-function/\">questions,它似乎你的问题是使用参数最大使用自定义的类时。我回答你的问题,并提供一种方式来使用你的类与在我的答案。

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天全站免登陆