【Python】for循环--内置函数range和enumerate的用法

       在使用Python进行数据分析时,不可避免的要进行for loop,小白之前到这种时候一直都是用range(len())的组合进行遍历,后来发现,Python内置函数enumerate也非常方便,下面就总结一下两种方法的用法:

1.Python range() 函数用法

语法:range(start, stop[, step])

参数说明:
start:下标起始值,默认是从 0 开始;
stop: 下标截止值,但不包括 stop。
step:步长,默认为1。如果想设置其他步长,可以:range(0,100,5)步长就是5

一般情况下,我们不会设定一个固定的截止数值,而是对一个数组、list进行遍历,下面来一个例子来说明:

values=['a','b','c']
for i in range(len(values)):
    print ("the result of index is %d,the result of element is %s" % (i,values[i]))

结果为:

the result of index is 0,the result of values is a
the result of index is 1,the result of values is b
the result of index is 2,the result of values is c

2.Python enumerate() 函数

语法:

enumerate(sequence, [start=0])

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
参数:
sequence :一个序列、迭代器或其他支持迭代对象。
start :下标起始值

上面的例子就可以写为:注意,这时每个下标对应的结果值可以直接取出,不需要用下标的方式来获取

values=['a','b','c']
for index, element in enumerate(values):
    print ("the result of index is %d,the result of element is %s" % (index,element))

结果为:

the result of index is 0,the result of element is a
the result of index is 1,the result of element is b
the result of index is 2,the result of element is c

比较起来,其实第二种方式比第一种更方便,大家可以多多使用第二种方法,阅读性和便利性都很好~

发布了92 篇原创文章 · 获赞 125 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/Jarry_cm/article/details/98509740
今日推荐