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] 注意普通參數與*和**參數公用的情況,一般將*和**參數放在參數列表最后。

[元組的情形] 

#! /usr/bin/python
# Filename: tuple_function.py
# 2010-7-19 wcdj
def powersum(power, *args):
    '''Return the sum of each argument raised
to specified power.'''
    
    total=0
    for i in args:
        total+=pow(i,power)
    return total
print 'powersum(2, 3, 4)==', powersum(2, 3, 4)
print 'powersum(2, 10)==', powersum(2, 10)
########
# output
########
powersum(2, 3, 4)==25
powersum(2, 10)==100 

 

[字典的情形]

 

#! /usr/bin/python
# Filename: dict_function.py
# 2010-7-19 wcdj
def findad(username, **args):
    '''find address by dictionary'''
    print 'Hello: ', username
    for name, address in args.items():
        print 'Contact %s at %s' % (name, address)
findad('wcdj', gerry='gerry@byteofpython.info', /
        wcdj='wcdj@126.com', yj='yj@gmail.com'

 

在gvim中的輸出結果:
gvim中的輸出結果

 

http://blog.csdn.net/delphiwcdj/article/details/5746560


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM