加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 有没有办法让for循环的运行计数不使用范围?

发布时间:2020-12-20 12:31:28 所属栏目:Python 来源:网络整理
导读:如果我有一个使用这样的范围的for循环: for x in range(10): 然后为了获得计数,它只是x.但是说我有一个使用列表的for循环: layer = [somedata,someotherdata...etc]for row in layer: print #the number the loop is on 有没有办法做到这一点,除了指定一个
如果我有一个使用这样的范围的for循环:

for x in range(10):

然后为了获得计数,它只是x.但是说我有一个使用列表的for循环:

layer = [somedata,someotherdata...etc]
for row in layer:
     print #the number the loop is on

有没有办法做到这一点,除了指定一个整数计数变量并逐渐递增它,像这样?

layer = [somedata]
count = 0
for row in layer:
    print count
    count += 1

解决方法

您可以使用枚举.这将为您提供每次迭代的计数和您正在迭代的值.

注意:像范围一样,您可以指定开始计数的索引.

for count,row in enumerate(layer):
    print count

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读