索引错误:从空列表中弹出

-1 投票
1 回答
12117 浏览
提问于 2025-04-18 08:38

我需要帮助。我不知道为什么会出现这个错误。错误出现在 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\n"%(src, dst, num, success)

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

    return success

#

1 个回答

1

lst 的元素比 num 少

可以使用

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

或者类似的方式

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

解释

#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

如果你这样做:

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

最后:

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

希望这能帮到你

撰写回答