Pop索引超出范围(python)

时间:2017-12-09 02:41:34

标签: python python-3.x indexing pop index-error

我是一名非常初学的程序员,我大约在3个月前开始。我正在为我的学校作业编写代码。它是桥接带宽问题。我在第28行得到索引错误,其中包含' IndexError:pop index超出范围' 我不知道如何解决这个问题。我也欢迎其他建议让我的代码更好。

顺便说一下,我的程序尚未完成。我需要写很多印刷语句。

# 1.The fastest two cross first
# 2.The fastest crosses back
# 3.The slowest two cross next
# 4.The fastest crosses back
# 5.The remaining two cross
import csv, random

locAtime = []
locAname = []
locBtime = []
locBname = []

#import csv file
with open('gNames.csv','r', encoding="latin-1") as csvfile:       
    reader = csv.reader(csvfile,delimiter=',')
    locAname = [''.join(x) for x in list(reader)]

locAtime = [i for i in range(len(locAname)+1)]

random.shuffle(locAtime)

timer = 0

while len(locAname) != 0:

    # 1. The fastest two cross first
    for i in range(2):
        idx = locAtime.index(min(locAtime))
        locBname.append(locAname.pop(idx))   #LINE 28 INDEX ERROR HAPPENS HERE
        locBtime.append(locAtime.pop(idx))

    timer += locBtime[-1]

    if len(locAname) == 0:
        break

    # 2. The fastest crosses back
    idx = locBtime.index(min(locBtime))    
    locAname.append(locBname.pop(idx))
    locAtime.append(locBtime.pop(idx))

    timer += locAtime[-1]

    #3. The slowest two cross next

    for i in range(2):
        idx = locAtime.index(max(locAtime))    
        locBname.append(locAname.pop(idx))
        locBtime.append(locAtime.pop(idx))

    timer += locBtime[-2]

    if len(locAname) == 0:
        break

    #4. The fastest crosses back
    idx = locBtime.index(min(locBtime))    
    locAname.append(locBname.pop(idx))
    locAtime.append(locBtime.pop(idx))

    timer += locAtime[-1]

1 个答案:

答案 0 :(得分:0)

尝试在第一个for循环(1)之后添加这个if语句

# 1. The fastest two cross first
for i in range(2):
    if i != 0: