文章来源于机器学习算法与Python实战,作者爱学习的胡同学

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

备注:公众号菜单包含了整理了一本AI小抄非常适合在通勤路上用学习

往期精彩回顾2019年公众号文章精选适合初学者入门人工智能的路线及资料下载机器学习在线手册深度学习在线手册AI基础下载(第一部分)备注:加入本站微信群或者qq群,请回复“加群”加入知识星球(4500+用户,ID:92416895),请回复“知识星球”

喜欢文章,点个在看

Python中enumerate函数的解释和可视化相关推荐

  1. Python中zip()函数的解释和可视化

    文章来源于机器学习算法与Python实战,作者爱学习的胡同学 zip()的作用 先看一下语法: zip(iter1 [,iter2 [...]]) -> zip object Python的内置 ...

  2. enumerate在java_Python中enumerate函数的解释和可视化

    enumerate() 的作用 在许多情况下,我们需要在迭代数据对性(即我们可以循环的任何对象)时获取元素的索引.实现预期结果的一种方法是: animals = ['dog', 'cat', 'mou ...

  3. python中map函数运行原理_Python中map函数的解释和可视化

    先重温一下迭代(Iteration).迭代器对象(iterable).迭代器(iterator )的概念: Iteration是计算机科学的通用术语,它是指对一组元素执行一项操作,一次执行一个元素.一 ...

  4. python zip是什么意思_Python中zip()函数的解释和可视化

    作者丨爱学习的胡同学 来源丨机器学习算法与Python实战(tjxj666) zip()的作用 先看一下语法: zip(iter1 [,iter2 [...]]) -> zip object P ...

  5. python中enumerate()函数_Python enumerate() 函数

    Python中的enumerate函数主要用于字符串.列表或元组的遍历时.一般的,当需要对字符串.列表或元组进行遍历的时候,最简单的方式如下(这里以list为例): l = [1,2,3,4,5] f ...

  6. python 中 enumerate() 函数使用

    描述 enumerate() 函数用于将一个可遍历的数据对象(如列表.元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中. Python 2.3. 以上版本可用,2. ...

  7. python中enumerate()函数

    enumerate()函数 概述: enumerate()函数表示将列表.字符串等可遍历的数据对象组成一个索引序列. 使用方法: 首先,创建一个列表: name=['唐三','小舞','慕白','二明 ...

  8. python 遍历函数用法_python中enumerate函数遍历元素用法分析

    本文实例讲述了python中enumerate函数遍历元素用法.分享给大家供大家参考,具体如下: enumerate函数用于遍历序列中的元素以及它们的下标 示例代码如下: i = 0 seq = [' ...

  9. python中set()函数的用法,python中set()函数简介及实例解析

    python中set()函数简介及实例解析 set函数也是python内置函数的其中一个,属于比较基础的函数.其具体介绍和使用方法,下面进行介绍. set() 函数创建一个无序不重复元素集,可进行关系 ...

最新文章

  1. 多媒体指令(灰度像素最大值)
  2. Java中String、StringBuffer和StringBuilder的区别
  3. JavaScript:事件冒泡和事件委托
  4. 如何取消linux响铃_linux初学者入门:VIM编辑简易指南(常用操作)
  5. (CodeForces 548B 暴力) Mike and Fun
  6. margin-top失效的解决方法
  7. github如何删除一个repository【找不到settings】
  8. 依赖包报错Invalid options object. Less Loader has been initialized using an options object that does not
  9. sys_brk分析 linux1.2.0版本,linux内存管理之sys_brk实现分析(续)
  10. js学习总结----浏览器滚动条卷去的高度scrolltop
  11. modalTransitionStyle各种present效果
  12. 你有没有思考过,特斯拉为什么先进?
  13. Cesium基础知识-创建3D地球
  14. python 方波信号_python实现周期方波信号频谱图
  15. 使用gmediarender-resurrect搭建DLNA音箱
  16. Unity Shader-Ambient Occlusion环境光遮蔽(AO贴图,GPU AO贴图烘焙,SSAO,HBAO)
  17. 二十八条改善 ASP 性能和外观的技巧
  18. 17 | 分布式安全:上百个分布式节点,不会出现“内奸”吗?
  19. FZU - 2062 - Suneast Yayamao
  20. EJB 3会话bean与Spring的区别

热门文章

  1. 获取安卓应用APK包名的方法
  2. VirtualBox COM对象获取失败
  3. 14 调整数组顺序使奇数位于偶数前面
  4. C#文件操作(IO流 摘抄)
  5. 软件测试作业1 -- 关于c++项目中类相互调用的问题与解决
  6. Android开发学习之路--Camera之初体验
  7. 宿舍助手app——个人工作第四天
  8. C#设置标记方法等为否决的不可用
  9. Selenium2Library关键字(1)
  10. Java语言基础JavaScript