是否有一种优雅的Pythonic方法来计算处理过的数据?

时间:2015-04-30 22:14:48

标签: python loops counter

我经常花费很多时间在循环中进行处理。以下方法是我如何跟踪处理的位置。在脚本运行时是否有更优雅的Pythonic计算处理数据的方法?

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

1 个答案:

答案 0 :(得分:5)

是的,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