python字典建構函式dict(mapping)解析

來源:互聯網
上載者:User

標籤:blog   ar   使用   sp   div   on   2014   art   log   

Python字典的建構函式有三個,dict()、dict(**args)、dict(mapping),當中第一個、第二個建構函式比較好理解也比較easy使用,

而dict(mapping)這個建構函式的使用比較難理解。

1 dict()建構函式能夠返回一個空的字典

In [7]: d = dict()In [8]: print d{}In [9]: 

2 dict(**arg)建構函式,傳入參數用賦值運算式,可多個賦值運算式,用逗號間隔就可以。

In [9]: d = dict(a = 12, b = 13, c = 15)In [10]: print d{'a': 12, 'c': 15, 'b': 13}In [11]: 

3 dict(mapping)構造python字典建構函式,怎麼傳入這個mapping參數呢?Python下的mapping究竟是什麼呢?

看下邊這個範例。

def fmap(a, b):         return (a, b)lik = range(1, 9) liv = list("abcdefgh")print map(fmap, lik, liv) 

執行結果例如以下

[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h')]

       map函數的作用是:每次從可迭代對象(這裡是列表lik和liv)取出一個元素值,經過fmap自己定義函數的處理後作為新的(返回)列表的元素,故這個map函數的操作方式非常像列表解析的概念。

       理解了map函數後,便可將返回值作為dict的傳入參數了,從而得到一個字典。

def fmap(a, b):        return (a, b)lik = range(1, 11)liv = list("abcdefghij")lim = map(fmap, lik, liv)d = dict(lim)print d

      運行結果例如以下所看到的:

{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j'}


以上通過map函數實現的方式,Python提供了還有一個函數zip,也可構造出一個mapping對象,代碼例如以下所看到的:

In [77]: k = list("abcdefghij")In [78]: print k['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']In [79]: v = range(11, 21)In [80]: print v[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]In [81]: m = zip(k,v)In [82]: print m[('a', 11), ('b', 12), ('c', 13), ('d', 14), ('e', 15), ('f', 16), ('g', 17), ('h', 18), ('i', 19), ('j', 20)]In [83]: d = dict(m)In [84]: print d{'a': 11, 'c': 13, 'b': 12, 'e': 15, 'd': 14, 'g': 17, 'f': 16, 'i': 19, 'h': 18, 'j': 20}


python字典建構函式dict(mapping)解析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.