IndexError: list index out of range Python Line 36

IndexError: list index out of range Python Line 36

import math

with open("input.txt", "r") as file:
    list = []
    for line in file:
        list += [line.strip()]

list1 = list[0].split(" ")
a = int(list1[0])
b = int(list1[1])

list2 = []
list3 = []
d = a + 1
c = 1

for i in range(1, a+1):
    list2.append(list[c])
    c = c + 1

for i in range(d+1, a+b+2):
    list3.append(list[d])
    d = d + 1

e = 0
f = 0
g = 1000000000000000
list6 = []

for i in range(0, b):
    for i in range(1, a):
        list4 = list3[e].split(" ")
        x = int(list4[0])
        y = int(list4[1])

        list5 = list2[f].split(" ")
        x1 = int(list5[0])
        y1 = int(list5[1])

        distance = math.sqrt(math.pow((x1 - x), 2) + math.pow((y1 - y), 2))
        list4.clear()
        list5.clear()
        f = f + 1
        if distance < g:
            g = distance
    e = e + 1
    list6.append(g)

print(list6)

当我启动程序时,总是出现“IndexError: list index out of range”。有人可以帮我解决这个问题。错误在第 36 行。

list5 = list2[f].split(" ")
IndexError: list index out of range

您永远不会重置 f。由于它处于嵌套循环中,即使在第一次完全执行内部循环之后,它也会继续增长。尝试在第一个循环的顶部将其重置为默认值:

import math

with open("input.txt", "r") as file:
    list = []
    for line in file:
        list += [line.strip()]

list1 = list[0].split(" ")
a = int(list1[0])
b = int(list1[1])

list2 = []
list3 = []
d = a + 1
c = 1

for i in range(1, a+1):
    list2.append(list[c])
    c = c + 1

for i in range(d+1, a+b+2):
    list3.append(list[d])
    d = d + 1

e = 0
g = 1000000000000000
list6 = []

for i in range(0, b):
    f = 0
    for i in range(1, a):
        list4 = list3[e].split(" ")
        x = int(list4[0])
        y = int(list4[1])

        list5 = list2[f].split(" ")
        x1 = int(list5[0])
        y1 = int(list5[1])

        distance = math.sqrt(math.pow((x1 - x), 2) + math.pow((y1 - y), 2))
        list4.clear()
        list5.clear()
        f = f + 1
        if distance < g:
            g = distance
    e = e + 1
    list6.append(g)

print(list6)