Python函数:enumerate()

Python基本函数: enumerate()

格式:enumerate()
注意:该文章用到文件读取语句open( ‘filepath’ , ‘r’) 以及 for循环。

一、函数说明

  • enumerate字面意思是枚举
  • enumerate多用于 得到for循环中的循环计数
  • 对于可迭代(iterator)或者 可遍历对象(如列表、字符串),enumerate可将其组成一个索引序列,利用它同时获得索引以及值
  • enumerate()返回的是一个enumerate对象
import numpy as np
import pandas as pd

In :       	a = np.random.randn(5)                   #随机生成5维向量
Out:      	[ 0.30719172 -0.64741878  0.37033298  0.10294567  0.15470246] 		

In :       	for index, value in enumerate(a):
    			print (index, value)
Out: 		0 0.30719172465861083                    #遍历enumerate(a),得到的结果前列是索引,后列是值
			1 -0.6474187776753292
			2 0.37033297887981476
			3 0.10294567431169596
			4 0.15470246163367815

二、函数用法

1、对于一般用法enumerate(xx)如下:

In :       	ex1 = ["This", "is", "an", "exercise"]
			for index, string in enumerate(ex1):
    			print (index, string)
Out: 		0 This
			1 is
			2 an
			3 exercise

2、enumerate还可以用到第二个参数,一般默认0,用来指定索引起始值
            格式:enumerate(xx, x)

In :       	ex1 = ["This", "is", "an", "exercise"]
			for index, string in enumerate(ex1,2):
    			print (index, string)
Out: 		2 This
			3 is
			4 an
			5 exercise

结果发现输出时起始的索引值由0变成2

3、可以用于统计文件的行数

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

最后输出的值即文件的行数

发布了36 篇原创文章 · 获赞 5 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_40520596/article/details/102756451