python 函式傳不定數量參數的方式 和 幾個重要的資料結構

不確定多少個參數會被傳入時, 可以用以下的寫法:

def say(greeting, *people):
    p = ', ' . join(people)
    msg = '%s: %s' % (greeting, p)
    print msg

ex:
say('Hello', 'eric', 'kevin')
--> Hello: eric, kevin

將參數存成一個tuple資料  --> ('eric', 'kevin')


不定參數也可以這樣操作:

def foo(name, **options):
    print 'Name: %s' % name
    if options.has_key('age'):
        print 'Age: %s' % options['age']
    if options.has_key('mail'):
        print 'Mail: %s' % options['mail']

ex:
foo('eric', mail='eric@foo.bar')
-->
Name: eric
Mail: eric@foo.bar

這種寫法會將參數存成一個dict資料型態 --> {'mail': 'eric@foo.bar'}

------------------------------------------------------------------------------------------------------------

List 資料型態: 可以用來表示串接在一起的資料(其內的元素可以是任何python的資料型態或是物件), 例如: a = [1, 3, 'abc', 7, 9, 3+2j]

Tuple 資料型態: 和list型態類似, 只是tuple是以小括號"()"包住, 最主要的差別是tuple資料是唯讀的, 一旦決定了就無法修改, 例如: b = (4,5,6)

Dict 資料型態: 是python 提供像是hash 或是mapping這樣的資料結構, 用來儲存key-value pair, list資料型態是以數字做為索引, dict 資料型態則是以key值做為索引

例如:
a = {'name': 'eric', 'email': 'eric@example.com'}
print a['name']
--> output 為 eric

Note: dict 資料型態的key一定要是字串資料

留言

熱門文章