Python在函数中使用*和**接收元组和列表

当要使函数接收元组或字典形式的参数 的时候,有一种特殊的方法,它分别使用*和**前缀 。这种方法在函数需要获取可变数量的参数 的时候特别有用。

[注意] 
[1] 由于在args变量前有*前缀 ,所有多余的函数参数都会作为一个元组存储在args中 。如果使用的是**前缀 ,多余的参数则会被认为是一个字典的健/值对 。
[2] 对于def func(*args):,*args表示把传进来的位置参数存储在tuple(元组)args里面。例如,调用func(1, 2, 3) ,args就表示(1, 2, 3)这个元组 。
[3] 对于def func(**args):,**args表示把参数作为字典的健-值对存储在dict(字典)args里面。例如,调用func(a='I', b='am', c='wcdj') ,args就表示{'a':'I', 'b':'am', 'c':'wcdj'}这个字典 。
[4] 注意普通参数与*和**参数公用的情况,一般将*和**参数放在参数列表最后。

[元组的情形] 

[python]  view plain  copy
  1. #! /usr/bin/python  
  2. # Filename: tuple_function.py  
  3. # 2010-7-19 wcdj  
  4. def powersum(power, *args):  
  5.     '''''Return the sum of each argument raised 
  6. to specified power.'''  
  7.       
  8.     total=0  
  9.     for i in args:  
  10.         total+=pow(i,power)  
  11.     return total  
  12. print 'powersum(2, 3, 4)==', powersum(234)  
  13. print 'powersum(2, 10)==', powersum(210)  
  14. ########  
  15. # output  
  16. ########  
  17. powersum(234)==25  
  18. powersum(210)==100   

[字典的情形]

[python]  view plain  copy
  1. #! /usr/bin/python  
  2. # Filename: dict_function.py  
  3. # 2010-7-19 wcdj  
  4. def findad(username, **args):  
  5.     '''''find address by dictionary'''  
  6.     print 'Hello: ', username  
  7.     for name, address in args.items():  
  8.         print 'Contact %s at %s' % (name, address)  
  9. findad('wcdj', gerry='[email protected]', /  
  10.         wcdj='[email protected]', yj='[email protected]'  

在gvim中的输出结果:
gvim中的输出结果

猜你喜欢

转载自blog.csdn.net/epeaktop/article/details/78433983