【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

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

 

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值