接受任何数量的参数的函数? [英] function that accepts any amount of arguments?
问题描述
如果我想要一个可以接受任何数量参数的函数我怎么做?$ / b
让我说我想要一个接受任何函数的函数平均值整数个数
并返回平均值。
if i want a function that can take any amount of arguments how do i
do?
lets say i want a function average that accepts any number of integers
and returns the average.
推荐答案
globalrev写道:
globalrev wrote:
如果我想要一个可以接受任何数量参数的函数我怎么做?b $ b呢?
if i want a function that can take any amount of arguments how do i
do?
在参数名称前加上星号。
Put an asterisk before the argument name.
假设我想要一个函数接受任意数量整数的平均值
并返回平均值。
lets say i want a function average that accepts any number of integers
and returns the average.
def avg(* args):
返还金额(args)/ len(args)
使用此代码有一些危险(至少有两个明显的危险),但是我会留下
,作为练习留给读者。
:)
Paul
def avg(*args):
return sum(args) / len(args)
There are some dangers (at least two glaring ones) with this code,
though, which I leave as an exercise for the reader.
:)
Paul
globalrev写道:
globalrev wrote:
if我想要一个可以接受任何数量参数的函数我怎么做?$ / b
假设我想要一个接受任意数量整数的函数平均值
并返回平均值。
if i want a function that can take any amount of arguments how do i
do?
lets say i want a function average that accepts any number of integers
and returns the average.
使用* args形式的参数 - 星号告诉解释器
将位置参数收集到元组中。未经测试:
def mean(* x):
总计= 0.0
for v in x:
总计+ = v
返回v / len(x)
问候
史蒂夫
-
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Use a parameter of the form *args - the asterisk tells the interpreter
to collect positional arguments into a tuple. Untested:
def mean(*x):
total = 0.0
for v in x:
total += v
return v/len(x)
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
globalrev < sk ******* @ yahoo.sewrote in message
news:4d *********************** *********** @ w7g2000h sa.googlegroups.com ...
|如果我想要一个可以接受任何数量参数的函数我该怎么做?
|吗?
|
|假设我想要一个接受任意数量整数的函数平均值
|并返回平均值。
要添加其他注释,请阅读函数defs的参考手册部分。
"globalrev" <sk*******@yahoo.sewrote in message
news:4d**********************************@w7g2000h sa.googlegroups.com...
| if i want a function that can take any amount of arguments how do i
| do?
|
| lets say i want a function average that accepts any number of integers
| and returns the average.
To add to the other comments, read the ref manual section of function defs.
这篇关于接受任何数量的参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!