Python的enumerate()函数在循环中的应用
Python笔记上曾提到,enumerate()函数是Python提供的一种在循环中获取索引和元素的方法,适用于多种数据类型。在本文中,我将介绍上述函数的具体使用方法,并述及一些例子。
enumerate()函数的基本用法
enumerate()函数用于将可迭代对象转为枚举对象,提供两个参数:iterable(可迭代对象)和start(索引的起始值)。当我们将某一可迭代对象(比如列表,元组或字符串)作为参数传递给enumerate()函数进行循环遍历时,可以同时访问每个元素及其对应的索引。
以下是语法:
enumerate(iterable, start=0)
其中,iterable 表示需要枚举的 L 列表,start 表示第一个枚举出来的元素的索引值,默认从 0 开始,可以不手动指定。
举个例子:我们可以遍历一个列表,并用 enumerate() 函数在循环中同时获取每个元素和它对应的索引。
fruits = ['apple', 'banana', 'mango', 'orange']
for index, fruit in enumerate(fruits):
print(index, fruit)
输出如下:
0 apple
1 banana
2 mango
3 orange
从输出结果来看,我们可以看到每行参数列表的第一项代表了元素的索引值,第二项代表了元素的值。
enumerate(iterable, start=0) 的流程也很简单:
1.获取可迭代对象 iterable 里面的每个元素;
2.给这个元素一个自增的索引(默认从 start=0 开始);
3.将此元素与索引组合为一个元组,并将其加入一个枚举对象;
4.重复关键步骤 1 到 3,直至可迭代对象里的所有元素都被构建成了枚举对象中的元组。
遍历字符串并计算元音字母数量
接着上文,我们可以在枚举表达式中添加其他代码,比如 if...else 语句,也可以计算可迭代对象中元素出现次数,或者计算满足特定条件的元素数量。
下面,让我们来看一下下列例子“遍历字符串并计算元音字母数量”的具体实现:
message = 'Python is an easy-to-learn and powerful language!'
count = 0
for index, letter in enumerate(message):
if letter in 'aeiouAEIOU':
count += 1
print('There are', count, 'vowels in the message.')
运行结果如下:
There are 17 vowels in the message.
代码的主要目的是如何计算给定字符串 message 中的元音字母的数量。通过将字符串 message 分成枚举表达式中的 index 和 letter,count 变量初始化为 0,for 循环检查字母是否是元音字母,如果是,count 将累加。一旦 for 循环完成,累加后的元音字母就被打印出来。
输出变量的索引和值
下面来看一个输出变量的索引和值的例子,可以对它们分别重复执行一些操作。假设我们现在有一个列表 colors,我们想要输出每个颜色和它的索引,并可根据需要对颜色进行任何处理。
colors = ['red', 'blue', 'green', 'yellow', 'orange']
for index, color in enumerate(colors):
print(f"At index {index} of colors: {color}")
输出如下:
At index 0 of colors: red
At index 1 of colors: blue
At index 2 of colors: green
At index 3 of colors: yellow
At index 4 of colors: orange
除此之外,我们也可以使用 if 语句和 continue 语句来跳过需要忽略的索引值。这个示例代码将过滤那些已被删除(赋值为 None)的颜色,只打印一个新列表中有颜色的项:
colors = ['red', 'blue', None, 'green', 'yellow', None, 'orange', None]
for index, color in enumerate(colors):
if color is None:
continue
print(f"Record found at offset {index}: {color}")
输出如下:
Record found at offset 0: red
Record found at offset 1: blue
Record found at offset 3: green
Record found at offset 4: yellow
Record found at offset 6: orange
总结
使用 Python 的 enumerate() 函数可以很方便地循环遍历元素和索引,从而进行一些累加或过滤操作。当我们需要在循环中同时访问可迭代对象的元素和索引值时,它是一个极好的工具。
