enumerate() 的作用
在許多情況下,我們需要在迭代數(shù)據(jù)對(duì)性(即我們可以循環(huán)的任何對(duì)象)時(shí)獲取元素的索引。實(shí)現(xiàn)預(yù)期結(jié)果的一種方法是:
animals = ['dog', 'cat', 'mouse']
for i in range(len(animals)):
print(i, animals[i])
輸出:
0 dog
1 cat
2 mouse
大多數(shù)C ++ / Java背景的開發(fā)人員都可能會(huì)選擇上述實(shí)現(xiàn),通過索引迭代數(shù)據(jù)對(duì)象的長(zhǎng)度是他們熟悉的概念。但是,這種方法效率很低。
我們可以使用enumerate()來實(shí)現(xiàn):
for i, j in enumerate(example):
print(i, j)
enumerate()提供了強(qiáng)大的功能,例如,當(dāng)您需要獲取索引列表時(shí),它會(huì)派上用場(chǎng):
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
案例研究1:枚舉字符串
字符串只是一個(gè)列表
為了更好地理解字符串枚舉,我們可以將給定的字符串想象為單個(gè)字符(項(xiàng))的集合。因此,枚舉字符串將為我們提供:
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:列舉列表
那么,我們應(yīng)該如何列舉一個(gè)列表呢?為了做到這一點(diǎn),我們可以利用for循環(huán)并遍歷每個(gè)項(xiàng)目的索引和值:
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開始,但是們經(jīng)常需要更改起始位置,以實(shí)現(xiàn)更多的可定制性。值得慶幸的是,enumerate()還帶有一個(gè)可選參數(shù)[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'
現(xiàn)在,修改上述代碼:1.起始索引可以為負(fù);2.省略start=則默認(rèn)從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:枚舉列表中的元組
讓我們提高一個(gè)檔次,將多個(gè)元組合并到一個(gè)列表中……我們要枚舉此元組列表。一種做法的代碼如下:
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:枚舉字典
枚舉字典似乎類似于枚舉字符串或列表,但事實(shí)并非如此,主要區(qū)別在于它們的順序結(jié)構(gòu),即特定數(shù)據(jù)結(jié)構(gòu)中元素的排序方式。
字典有些隨意,因?yàn)樗鼈兊捻?xiàng)的順序是不可預(yù)測(cè)的。如果我們創(chuàng)建字典并打印它,我們將得到一種結(jié)果:
translation = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print(translation)
# Output on our computer: {'one': 'uno', 'two': 'dos', 'three': 'tres'}
但是,如果打印此詞典,則順序可能會(huì)有所不同!
由于索引無法訪問字典項(xiàng),因此我們必須利用for循環(huán)來迭代字典的鍵和值。該key — value對(duì)稱為item,因此我們可以使用.items()方法:
animals = {'cat': 3, 'dog': 6, 'bird': 9}
for key, value in animals.items():
print(key, value)
輸出將是:
cat 3
dog 6
bird 9
本文由博客一文多發(fā)平臺(tái) OpenWrite 發(fā)布!
審核編輯 黃昊宇
-
機(jī)器學(xué)習(xí)
+關(guān)注
關(guān)注
66文章
8434瀏覽量
132865 -
python
+關(guān)注
關(guān)注
56文章
4804瀏覽量
84903 -
深度學(xué)習(xí)
+關(guān)注
關(guān)注
73文章
5511瀏覽量
121363
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論