如果我在if语句集之前打印pts [0] [0],则语句print(“ final pts:”,pts)总是打印一个空数组。但是,如果我在一组if语句之后打印pts [0] [0],则行print(“ final pts:”,pts)将显示正确的值。
我相信这与pts.pop(0)行有关,因为这也无法正常工作。当我= 2时,它无法正常工作。
任何人都可以复制此结果吗?为什么打印语句会影响列表值?
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import numpy as np
x = [10, 24, 23, 23, 3]
y = [12, 2, 3, 4, 2]
skpoints = list(zip(x, y))
for i in skpoints:
print(i)
limits = np.arange(-1, 2)
pts = []
cutoff = 10
master = []
for i in range(len(skpoints)):
pts = []
temp = 1000
print("\ni: ", i)
for j in limits:
try:
dist = np.sqrt((skpoints[i][0] - skpoints[i + j][0]) ** 2 + (skpoints[i][1] - skpoints[i + j][1]) ** 2)
print(dist)
if 0 < dist < temp and (skpoints[i] and skpoints[i+j]) not in pts and dist < cutoff:
print('pts before if statements', pts[0])
# if its empty, add point right away
if not master or not pts:
pts.append([dist, skpoints[i], skpoints[i + j]])
# if dist is smaller than previous distance, replace distance and points
elif dist < pts[0][0]:
pts.pop(0)
pts.append([dist, skpoints[i], skpoints[i + j]])
elif dist == temp and (skpoints[i] and skpoints[i+j]) not in pts:
pts.append([skpoints[i], skpoints[i + j]])
temp = dist
print('pts after if statements', pts[0])
except IndexError:
j -= 1
print("final pts: ", pts)
问题是您的空白try..catch
;您正在默默地吞下所有异常,甚至没有打印它们的任何痕迹,这使得调试变得非常困难。
如果print('pts before if statements', pts[0])
为空,IndexError
语句将引发pts
异常,这会绕过循环主体的其余部分,因此导致完全不同的结果。