Python標準庫:內建函數enumerate(iterable, start=0),enumerateiterable

來源:互聯網
上載者:User

Python標準庫:內建函數enumerate(iterable, start=0),enumerateiterable

本函數是把可迭代對象轉換為枚舉對象。iterable是可迭代參數,比如像列表、數組、字典等對象;start是枚舉的起始值,預設是從0開始。這個函數實現原理是這樣,從迭代對象的方法__next__()取得一項值,然後就對參數start開始計數,每取一項增加1,產生一個元組返回。

本函數實現原理,大體上可以用下面的代碼來表示:

def enumerate(sequence, start=0):

    n = start

    for elem in sequence:

        yield n, elem

        n += 1

下面就來看看例子:

#enumerate()l = ['a', 'b', 'c']print(list(enumerate(l)))t = ('快樂', '高興', '開心')print(list(enumerate(t)))d = {'深圳':1, '廣州':2, '珠海':3}print(list(enumerate(d, 2)))s = '深圳是一個高科技的超級城市,人口擁有1800萬人'print(list(enumerate(s, 1)))

結果輸出如下:

[(0, 'a'), (1, 'b'), (2, 'c')]

[(0, '快樂'), (1, '高興'), (2, '開心')]

[(2, '深圳'), (3, '珠海'), (4, '廣州')]

[(1, '深'), (2, '圳'), (3, '是'), (4, '一'), (5, '個'), (6, '高'), (7, '科'), (8, '技'), (9, '的'), (10, '超'), (11, '級'), (12, '城'), (13, '市'), (14, ','), (15, '人'), (16, '口'), (17, '擁'), (18, '有'), (19, '1'), (20, '8'), (21, '0'), (22, '0'), (23, '萬'), (24, '人')]



蔡軍生 QQ:9073204  深圳

聯繫我們

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