为什么值通过条件后我的while循环仍然运行

时间:2020-02-28 16:30:42

标签: python while-loop

因此,我开始进行一个项目以比较2个人的忙碌时间,并输出一个列表,其中包含可供他们安排约会的可用时间 输入:

Person 1 = [["9:00", "10:30"], ["12:00", "13:00"], ["16:00", "18:00"]]
Person 2 = [["10:00", "11:30"], ["12:30", "14:30"], ["14:30", "15:00"], ['16:00', '17:00']]

输出:

list = [["11:30","1200"],["15:00","16:00"]]
def Gettime(time1, time2):
    hour1, minutes1 = time1.split(":")
    hour2, minutes2 = time2.split(":")
    int_time1 = int(hour1) * 60 + int(minutes1)
    int_time2 = int(hour2) * 60 + int(minutes2)
    if int_time1 <= int_time2:
        return 1
    elif int_time1 > int_time2:
        return 2
    else:
        return 0


def FreeTime(sch1, sch2):
    list_nottime = []
    p1 = 0
    p2 = 0
    x = 0
    y = 0
    #while p2 < len(sch2) :
        #while p1 < len(sch1):
    while p1 < len(sch1) or p2 <len(sch2):
         if Gettime(sch1[p1][x], sch2[p2][y]) == 1:
            #print(sch1[p1][x], sch2[p2][y])
            list_nottime.append(sch1[p1][x])
            x += 1
            if x == 2:
                x = 0
                p1 += 1

         if Gettime(sch1[p1][x], sch2[p2][y]) == 2:
            #print(sch1[p1][x], sch2[p2][y])
            list_nottime.append(sch2[p2][y])
            y += 1
            if y == 2:
                y = 0
                p2 += 1

因此,在此结束时(在上方)p2 == 4,而while条件为p2 < len(Sch2)(等于4) 并且它仍然运行循环然后出错。 请检查并修复它,谢谢你们!!!(我不是母语人士,所以我的英语不好)

1 个答案:

答案 0 :(得分:1)

因此,问题出在调用第二个while循环之前,您正在递增p1的值,并且第二个while循环中的条件访问了sch[p1],这可能超出了给定数组。您需要将p1保存在一个临时变量中,并使用该值代替,然后再更新p1的值。

或者您需要一个条件来检查边缘或边界情况。对于p2也是一样,在第二个内部循环中将其递增,而第一个可能会尝试在索引超出范围的情况下对其进行访问。