ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【test】Enumerate 用法实例

2022-01-07 23:06:37  阅读:205  来源: 互联网

标签:index Enumerate list 索引 计数器 实例 enumerate test line


enumerate可以做什么?

1. 如何理解enumerate?

enumerate()是python的内置函数,用相当于给可迭代的对象(iterable object,比如string, list, dict, tuple, set等)增加了一个计数器。可以理解为带计数器的列表,字典,元组等。

2. 对可迭代对象进行索引

list_a = ['this', 'is', 'a', 'test']
list_b= list(enumerate(list_a, start =10))  # 两个参数,第一个参数为可迭代对象;第二个参数为计数器的起始值
list_c= list(enumerate(list_a, start =20))
print (list_b)
print(list_c)

print(type(enumerate(list_a)))  # 测试enumerate()返回数据类型

运行输出结果:

[(10, 'this'), (11, 'is'), (12, 'a'), (13, 'test')]
[(20, 'this'), (21, 'is'), (22, 'a'), (23, 'test')]
<class 'enumerate'>

Python3在线测试工具

用for循环遍历enumerate()中的索引和值,代码如下:

list_a = ['this', 'is', 'a', 'test']

for index, value in enumerate(list_a, start=100):
    print(f'计数器索引号码为:{index}。\t\t 数据值为{value}。')

 运行输出结果如下:

计数器索引号码为:100。         数据值为this。
计数器索引号码为:101。         数据值为is。
计数器索引号码为:102。         数据值为a。
计数器索引号码为:103。         数据值为test。

3. 对读取到的文件行进行索引

更进一步,我们可以读取text文件中的行,并用enumerate()方法对行进行索引。

使用方法 :enumerate(filepath, start)

参数1:filepath = open('example.txt','r'),默认为项目路径,以只读方式打开example.txt文件。example.txt文件内容如下:

this is line one.
this is line two.
this is line three.
this is line four.

参数2:start默认为0,可以自行指定

用for循环遍历enumerate,具体代码如下:

for index, line in enumerate(open('example.txt', 'r'), start=100):
    print (f'The index of this line is {index} :', line)

 运行结果如下:

The index of this line is 100 : this is line one.

The index of this line is 101 : this is line two.

The index of this line is 102 : this is line three.

The index of this line is 103 : this is line four.

标签:index,Enumerate,list,索引,计数器,实例,enumerate,test,line
来源: https://blog.csdn.net/climber1121/article/details/122373625

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有