Python中enumerate函数的解释和可视化

简介: Python中enumerate函数的解释和可视化

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:枚举字符串


640.png


字符串只是一个列表


为了更好地理解字符串枚举,我们可以将给定的字符串想象为单个字符(项)的集合。因此,枚举字符串将为我们提供:

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:列举列表


640.png

那么,我们应该如何列举一个列表呢?为了做到这一点,我们可以利用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:自定义起始索引


640.png


我们可以看到枚举从索引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:枚举列表中的元组


640.png

让我们提高一个档次,将多个元组合并到一个列表中……我们要枚举此元组列表。一种做法的代码如下:


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:枚举字典

640.png

枚举字典似乎类似于枚举字符串或列表,但事实并非如此,主要区别在于它们的顺序结构,即特定数据结构中元素的排序方式。


字典有些随意,因为它们的项的顺序是不可预测的。如果我们创建字典并打印它,我们将得到一种结果:


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
相关文章
|
2月前
|
数据采集 数据可视化 搜索推荐
Python数据分析全流程指南:从数据采集到可视化呈现的实战解析
在数字化转型中,数据分析成为企业决策核心,而Python凭借其强大生态和简洁语法成为首选工具。本文通过实战案例详解数据分析全流程,涵盖数据采集、清洗、探索、建模、可视化及自动化部署,帮助读者掌握从数据到业务价值的完整技能链。
318 0
|
2月前
|
PHP Python
Python format()函数高级字符串格式化详解
在 Python 中,字符串格式化是一个重要的主题,format() 函数作为一种灵活且强大的字符串格式化方法,被广泛应用。format() 函数不仅能实现基本的插入变量,还支持更多高级的格式化功能,包括数字格式、对齐、填充、日期时间格式、嵌套字段等。 今天我们将深入解析 format() 函数的高级用法,帮助你在实际编程中更高效地处理字符串格式化。
241 0
|
2月前
|
存储 数据可视化 BI
Python可视化应用——学生成绩分布柱状图展示
本程序使用Python读取Excel中的学生成绩数据,统计各分数段人数,并通过Matplotlib库绘制柱状图展示成绩分布。同时计算最高分、最低分及平均分,实现成绩可视化分析。
149 0
|
28天前
|
数据采集 数据可视化 API
驱动业务决策:基于Python的App用户行为分析与可视化方案
驱动业务决策:基于Python的App用户行为分析与可视化方案
|
2月前
|
索引 Python 容器
[oeasy]python096_列表_计数函数_count
本教程详细介绍了Python中列表的计数方法`count`,包括其基本用法、与`len`函数的区别,以及如何结合索引操作查找和删除特定元素。同时探讨了字符串对象的`count`方法,并通过实例演示了如何统计字符出现次数。
52 7
|
2月前
|
机器学习/深度学习 数据处理 索引
Python内置函数:面试通关的49个秘密武器
本文精选49个Python高频面试内置函数,涵盖数值处理、类型转换、序列操作、字典集合、函数式编程及高级特性,结合真实代码案例解析底层逻辑与应用场景,助你提升开发效率,轻松应对技术面试。
56 1
|
1月前
|
数据采集 索引 Python
Python Slice函数使用教程 - 详解与示例 | Python切片操作指南
Python中的`slice()`函数用于创建切片对象,以便对序列(如列表、字符串、元组)进行高效切片操作。它支持指定起始索引、结束索引和步长,提升代码可读性和灵活性。
|
2月前
|
存储 数据采集 数据可视化
Python自动化分析知网文献:爬取、存储与可视化
Python自动化分析知网文献:爬取、存储与可视化
|
3月前
|
数据采集 Web App开发 自然语言处理
利用Python构建今日头条搜索结果的可视化图表
利用Python构建今日头条搜索结果的可视化图表
|
3月前
|
API Python
Python 的内建函数
Python 的内置函数列表,方便查询使用方法。

热门文章

最新文章

推荐镜像

更多