如何透過 enumerate 函式建立 Python 字典?


Python enumerate() 函式對任何可迭代型別進行引數並返回 enumerate 物件,可透過它遍歷可迭代型別。它在可迭代物件(如 列表元組字串)中包含索引和相應的專案。

然後,使用字典解析將包含索引和值的此類 enumerate 物件轉換為 字典

>>> l1=['aa','bb','cc','dd']
>>> enum=enumerate(l1)
>>> enum

>>> d=dict((i,j) for i,j in enum)
>>> d
{0: 'aa', 1: 'bb', 2: 'cc', 3: 'dd'}

透過我們循序漸進的 Python 教程 來學習 Python。

更新時間: 2023-09-09

4K + 瀏覽次數

開啟你的 職業

完成課程獲得認證

立即開始
廣告
© . All rights reserved.