试图从一个数字倒数,而不是工作

时间:2014-11-10 18:35:54

标签: python for-loop count

def countdownList(l):  # 3. prints number of files left to process
    count = len(l)
    count = count - 1
    print count, " files left to go."
    if count == 0:
        print "Finished!"

当放置在for循环中时,该函数应该从正在处理的文件数减少到零。它无法识别行count = count - 1,因此如果有41个文件,则会打印41 files left to go 41次。

2 个答案:

答案 0 :(得分:0)

当您调用该函数时,每次循环时,

count = len(l)会一直将count重置为41。您需要在函数内部循环或从每次调用中删除元素。

l = [1,2,3]

for x in l:
    process(x)
    countdownList(l)
    l.pop(0) # shorten list by 1 each iteration

或者只使用枚举:

l = [1,2,3]

for ind, x in enumerate(l):
    print len(l) - ind, " files left to go." 
    process(x)

答案 1 :(得分:0)

替换下面的代码行并将其放在函数之外:

count = len(l)

为:

count = len(l)
def countdownList(l):  # 3. prints number of files left to process
    global count
    count = count - 1
    print count, " files left to go."
    if count == 0:
        print "Finished!"