Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

python - IndexError: pop from empty list

I need help. I have no idea why I am getting this error. The error is in fname = 1st.pop()

for i in range(num) :
        fname = lst.pop()
        lTransfer   = [(os.path.join(src, fname),           os.path.join(dst, fname)),
                       (os.path.join(src, fname) + ".md5",  os.path.join(dst, fname) + ".md5")]
        for tFiles in lTransfer:
            #
            # copy the file
            #
            try :
                shutil.copyfile(tFiles[0], tFiles[1])
                os.chmod(tFiles[1], 0o777)
                success += 1
            except :
                ErrList.append(sys.exc_info())
                print(ErrList[-1])
                x = 0

    if success != num:
        msg  = "CopyRandomFilesToFolder src=%s, dst=%s, desired count=%d, Success=%d
"%(src, dst, num, success)

        self._oLogger.LocalWriteLog(self._testname, 'CCmgCefHelper', msg, 0)

    return success

#

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

lst has less elements than num

use

for i in range(min(num, len(lst))):`

or something like

for fname in reversed(lst):# reversed to continue the pop order
   #your code

Explanation

#lets say we have
num = 4
data = [1,2,3]

for i in range(num): # range(4) = [0,1,2,3] so it witl repeat you code 4 times
    data.pop() #remove last element
#first 3 times, it works, but at the last one 'data' is empty, so you get an exception

if you do:

for i in range(min(num , len(data))):
# min(num , len(data)) = min(4,3) = 3
# so you get the corrent number of iterations

Finally:

for fname in reversed(data):
#is the same to
for fname in [3,2,1]:
#'reversed' just change the order of your list
#so it will work in this order, 3, 2 and finishes with 1

Hope it helps


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...