我经常花费很多时间在循环中进行处理。以下方法是我如何跟踪处理的位置。在脚本运行时是否有更优雅的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
答案 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
。