Python在函數中使用*和**接收元組和列表

來源:互聯網
上載者:User

標籤:sum   delphi   ecif   sdn   function   print   file   spec   usr   

當要使函數接收元組或字典形式的參數 的時候,有一種特殊的方法,它分別使用*和**首碼 。這種方法在函數需要擷取可變數量的參數的時候特別有用。

[注意] 
[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 wcdjdef powersum(power, *args):    ‘‘‘Return the sum of each argument raisedto specified power.‘‘‘        total=0    for i in args:        total+=pow(i,power)    return totalprint ‘powersum(2, 3, 4)==‘, powersum(2, 3, 4)print ‘powersum(2, 10)==‘, powersum(2, 10)######### output########powersum(2, 3, 4)==25powersum(2, 10)==100 

 

[字典的情形]

 

#! /usr/bin/python# Filename: dict_function.py# 2010-7-19 wcdjdef 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=‘[email protected]‘, /        wcdj=‘[email protected]‘, yj=‘[email protected]‘

 

在gvim中的輸出結果:

 

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

Python在函數中使用*和**接收元組和列表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.