Python 3.7 中影响数组值的打印语句顺序
Order of print statements affecting array values in Python 3.7
如果我在 if 语句集之前打印 pts[0][0]
,语句 print("final pts: ", pts)
总是打印一个空数组。但是,如果我在一组 if 语句之后打印 pts[0][0]
,则 print("final pts: ", pts)
行会显示正确的值。
我认为它与 pts.pop(0)
行有关,因为它也不能正常工作。当 i = 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
;你默默地吞下了所有异常,甚至没有打印它们的任何痕迹,这使得调试变得更加困难。
如果 pts
为空,print('pts before if statements', pts[0])
语句将引发 IndexError
异常,这会绕过循环体的整个其余部分,从而导致完全不同的结果。
如果我在 if 语句集之前打印 pts[0][0]
,语句 print("final pts: ", pts)
总是打印一个空数组。但是,如果我在一组 if 语句之后打印 pts[0][0]
,则 print("final pts: ", pts)
行会显示正确的值。
我认为它与 pts.pop(0)
行有关,因为它也不能正常工作。当 i = 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
;你默默地吞下了所有异常,甚至没有打印它们的任何痕迹,这使得调试变得更加困难。
如果 pts
为空,print('pts before if statements', pts[0])
语句将引发 IndexError
异常,这会绕过循环体的整个其余部分,从而导致完全不同的结果。