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

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

概述如果我有一个使用这样的范围的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 = 0for row in layer:    print count    count += 1
解决方法 您可以使用枚举.这将为您提供每次迭代的计数和您正在迭代的值.

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

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

以上是内存溢出为你收集整理的python – 有没有办法让for循环的运行计数不使用范围?全部内容,希望文章能够帮你解决python – 有没有办法让for循环的运行计数不使用范围?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1194938.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存