[Python] enumerate()函数

山茶花开时。 已于 2022-06-05 19:13:03 修改
于 2022-02-09 21:35:52 首次发布
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中
语法
enumerate(sequence, [start=0])
参数
sequence:一个序列、迭代器或其他支持迭代对象
start:下标起始位置
返回值
返回enumerate(枚举)对象
seasons = ['Spring', 'Summer', 'Autumn', 'Winter']
print(list(enumerate(seasons)))
print(list(enumerate(seasons, start=1)))
'普通的for循环
i = 0
seq = ['one', 'two', 'three']
for element in seq:
print(i, seq[i])
i = i + 1
for循环使用enumerate
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
print(i, element)
扩展练习:将学生成绩从大到小排名,并依次打印出来
score = [90, 89, 56, 78, 99]
score = [90, 89, 56, 78, 99]
sort_s = sorted(score, reverse=True)
index = 1
for i in sort_s:
print('第{}名:'.format(index),i)
index = index + 1
for i, j in enumerate(sort_s, start = 1):
print('第{}名:'.format(i),j)
第1名: 99
第2名: 90
第3名: 89
第4名: 78
第5名: 56
'相关知识
Python如何列出数组并使其成为枚举
python函数基本操作
Python快速入门
python font函数
理解Python中列表/字典/元组/集合
Python中函数加括号和不加括号的区别
python 使用Tensorflow训练BP神经网络实现鸢尾花分类
Python函数知识集锦(一)
python内置函数可以返回列表、元组
SKYNE/python
原文链接: [Python] enumerate()函数 https://m.huajiangbk.com/newsview1171799.html
| 上一篇: 令是法律法规吗 | 下一篇: 去法院起诉要花多少钱 |



