Python中enumerate函數的解釋和可視化

  • 2020 年 2 月 12 日
  • 筆記

enumerate() 的作用

在許多情況下,我們需要在迭代數據對性(即我們可以循環的任何對象)時獲取元素的索引。實現預期結果的一種方法是:

animals = ['dog', 'cat', 'mouse']  for i in range(len(animals)):      print(i, animals[i])  

輸出:

0 dog  1 cat  2 mouse  

大多數C ++ / Java背景的開發人員都可能會選擇上述實現,通過索引迭代數據對象的長度是他們熟悉的概念。但是,這種方法效率很低。我們可以使用enumerate()來實現:

for i, j in enumerate(example):      print(i, j)  

enumerate()提供了強大的功能,例如,當您需要獲取索引列表時,它會派上用場:

(0, seq[0]), (1, seq[1]), (2, seq[2]), ...  

案例研究1:枚舉字符串

字符串只是一個列表

為了更好地理解字符串枚舉,我們可以將給定的字符串想像為單個字符(項)的集合。因此,枚舉字符串將為我們提供:

1.字符的索引。2.字符的值。

word = "Speed"  for index, char in enumerate(word):      print(f"The index is '{index}' and the character value is '{char}'")  

輸出:

The index is '0' and the character value is 'S'  The index is '1' and the character value is 'p'  The index is '2' and the character value is 'e'  The index is '3' and the character value is 'e'  The index is '4' and the character value is 'd'  

案例研究2:列舉列表

那麼,我們應該如何列舉一個列表呢?為了做到這一點,我們可以利用for循環並遍歷每個項目的索引和值:

sports = ['soccer', 'basketball', 't`  ennis']  for index, value in enumerate(sports):      print(f"The item's index is {index} and its value is '{value}'")  

輸出:

The item's index is 0 and its value is 'soccer'  The item's index is 1 and its value is 'basketball'  The item's index is 2 and its value is 'tennis'  

案例研究3:自定義起始索引

我們可以看到枚舉從索引0開始,但是們經常需要更改起始位置,以實現更多的可定製性。值得慶幸的是,enumerate()還帶有一個可選參數[start]

enumerate(iterable, start=0)  

可以用來指示索引的起始位置,方法如下:

students = ['John', 'Jane', 'J-Bot 137']  for index, item in enumerate(students, start=1):      print(f"The index is {index} and the list element is '{item}'")  

輸出:

The index is 1 and the list element is 'John'  The index is 2 and the list element is 'Jane'  The index is 3 and the list element is 'J-Bot 137'  

現在,修改上述代碼:1.起始索引可以為負;2.省略start=則默認從0索引位置開始。

teachers = ['Mary', 'Mark', 'Merlin']  for index, item in enumerate(teachers, -5):      print(f"The index is {index} and the list element is '{item}'")  

輸出:

The index is -5 and the list element is 'Mary'  The index is -4 and the list element is 'Mark'  The index is -3 and the list element is 'Merlin'  

案例研究4:枚舉元組

使用枚舉元組遵循與枚舉列表相同的邏輯:

colors = ('red', 'green', 'blue')  for index, value in enumerate(colors):      print(f"The item's index is {index} and its value is '{value}'")  

輸出:

The item's index is 0 and its value is 'red'  The item's index is 1 and its value is 'green'  The item's index is 2 and its value is 'blue'  

案例研究5:枚舉列表中的元組

讓我們提高一個檔次,將多個元組合併到一個列表中……我們要枚舉此元組列表。一種做法的代碼如下:

letters = [('a', 'A'), ('b', 'B'), ('c', 'C')]  for index, value in enumerate(letters):      lowercase = value[0]      uppercase = value[1]      print(f"Index '{index}' refers to the letters '{lowercase}' and '{uppercase}'")  

但是,元組拆包被證明是一種更有效的方法。比如:

letters = [('a', 'A'), ('b', 'B'), ('c', 'C')]  for i, (lowercase, uppercase) in enumerate(letters):      print(f"Index '{i}' refers to the letters '{lowercase}' and '{uppercase}'")  

輸出:

Index '0' refers to the letters 'a' and 'A'  Index '1' refers to the letters 'b' and 'B'  Index '2' refers to the letters 'c' and 'C'  

案例研究6:枚舉字典

枚舉字典似乎類似於枚舉字符串或列表,但事實並非如此,主要區別在於它們的順序結構,即特定數據結構中元素的排序方式。

字典有些隨意,因為它們的項的順序是不可預測的。如果我們創建字典並打印它,我們將得到一種結果:

translation = {'one': 'uno', 'two': 'dos', 'three': 'tres'}  print(translation)  # Output on our computer: {'one': 'uno', 'two': 'dos', 'three': 'tres'}  

但是,如果打印此詞典,則順序可能會有所不同!

由於索引無法訪問字典項,因此我們必須利用for循環來迭代字典的鍵和值。該key — value對稱為item,因此我們可以使用.items()方法:

animals = {'cat': 3, 'dog': 6, 'bird': 9}  for key, value in animals.items():      print(key, value)  

輸出將是:

cat 3  dog 6  bird 9