This question already has answers here:
Loop through list with both content and index [duplicate]
(6个答案)
四年前关闭。
我经常在循环中执行耗时的处理步骤。下面的方法是如何跟踪处理的位置。在脚本运行时,是否有一种更优雅的、python式的方法来计算处理数据?
n_items = [x for x in range(0,100)]

counter = 1
for r in n_items:
    # Perform some time consuming task...
    print "%s of %s items have been processed" % (counter, len(n_items))
    counter = counter + 1

最佳答案

是的,enumerate是为这个而构建的:

for i,r in enumerate(n_items,1):
    # Perform some time consuming task
    print('{} of {} items have been processed'.format(i, len(n_items)))

第二个参数确定i的起始值,默认为0

10-05 21:20
查看更多