高手帮 解释下 这段python 代码

Python017

高手帮 解释下 这段python 代码,第1张

def fun(*arg):

*arg 代表可变个数参数 fun(something,something)

def fun(**arg):

** arg 允许键值对的可变个数参数 调用时fun(arg1 = something,arg2 = something)

看下面、。。。。

How to use *argsand **kwargs in Python

Date: 2008-01-03 | Modified:2012-12-20 | Tags:core,python | 94 Comments

Or,How to use variable length argumentlists in Python.

The special syntax,*argsand**kwargsin function definitions is used to pass a variable numberof arguments to a function. The single asterisk form (*args) is used to pass anon-keyworded, variable-length argument list, and the double asteriskform is used to pass akeyworded, variable-length argument list. Here is an example ofhow to use the non-keyworded form. This example passes one formal (positional)argument, and two more variable length arguments.

deftest_var_args(farg,*args):

print"formalarg:",farg

forarginargs:

print"another arg:",arg

test_var_args(1,"two",3)

Results:

formal arg: 1

another arg: two

another arg: 3

Here is an example of how to use the keyworded form.Again, one formal argument and two keyworded variable arguments are passed.

deftest_var_kwargs(farg,**kwargs):

print"formalarg:",farg

forkeyinkwargs:

print"another keyword arg:%s:%s"%(key,kwargs[key])

test_var_kwargs(farg=1,myarg2="two",myarg3=3)

Results:

formal arg: 1

another keyword arg: myarg2: two

another keyword arg: myarg3: 3

Using*argsand**kwargswhencallinga function

This special syntax can be used, not only in functiondefinitions, but also whencallinga function.

deftest_var_args_call(arg1,arg2,arg3):

print"arg1:",arg1

print"arg2:",arg2

print"arg3:",arg3

args=("two",3)

test_var_args_call(1,*args)

Results:

arg1: 1

arg2: two

arg3: 3

Here is an example using the keyworded form when callinga function:

deftest_var_args_call(arg1,arg2,arg3):

print"arg1:",arg1

print"arg2:",arg2

print"arg3:",arg3

kwargs={"arg3":3,"arg2":"two"}

test_var_args_call(1,**kwargs)

Results:

arg1: 1

arg2: two

arg3: 3

argmax是一种对函数求参数(集合)的函数。当有另一个函数y=f(x)时,若有结果x0=argmax(f(x)),则表示当函数f(x)取x=x0的时候,得到f(x)取值范围的最大值。

若有多个点使得f(x)取得相同的最大值,那么argmax(f(x))的结果就是一个点集。换句话说,argmax(f(x))是使得f(x)取得最大值所对应的变量点x(或x的集合)。arg即argument,此处意为“自变量”。

max和argmax:

y = f(t)是一般常见的函数式,如果给定一个t值,f(t)函数式会赋一个值给y。

y = max f(t)代表:y是f(t)函式所有的值中最大的output。

y = argmax f(t)代表:y是f(t)函式中,会产生最大output的那个参数t。