Python enumerate

一、定义

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

二、语法

enumerate(sequence[,start=0])

sequence:可迭代对象

start:开始下标

返回枚举(enumerate)对象

三、示例

1.

seasons = ["", "", "", ""]
one_var = enumerate(seasons)
print(one_var)  # <enumerate object at 0x00000263E880E6C0>
print(list(one_var))  # [(0, '春'), (1, '夏'), (2, '秋'), (3, '冬')]
seasons ={"Spring": "", "Summer": "", "Autumn": "", "Winter": ""}
one_var = enumerate(seasons,start=2)
print(dict(one_var))  # {2: 'Spring', 3: 'Summer', 4: 'Autumn', 5: 'Winter'}

 

2.for循环使用enumerate:

seasons = ["", "", "", ""]
for key, value in enumerate(seasons,start=2):
    print(f"key:{key},value{value:}")

key:2,value春
key:3,value夏
key:4,value秋
key:5,value冬

 

3.统计文件中的行数:

count = 0
for index, line in enumerate(open(filepath,'r')): 
   count += 1

也可以:

count = len(open(filepath, 'r').readlines())

 

posted on 2019-07-09 00:27  青柠锦鲤  阅读(180)  评论(0编辑  收藏  举报