为了账号安全,请及时绑定邮箱和手机立即绑定

在 Python 3.7 中影响数组值的打印语句顺序

在 Python 3.7 中影响数组值的打印语句顺序

翻翻过去那场雪 2022-07-26 10:26:12
如果我pts[0][0]在 if 语句集之前打印,则该语句print("final pts: ", pts)总是打印一个空数组。但是,如果我在 if 语句集之后打印pts[0][0],则该行将print("final pts: ", pts)显示正确的值。我相信它与这pts.pop(0)条线有关,因为它也不能正常工作。当 i = 2 时它不能正常工作。谁能重现这个结果?为什么 print 语句会影响列表值?from matplotlib.lines import Line2Dimport matplotlib.pyplot as pltimport numpy as npx = [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 = 10master = []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)
查看完整描述

1 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

问题是你的空白try..catch;您正在默默地吞下任何和所有异常,甚至没有打印任何痕迹,这使得调试变得更加困难。

如果为空,该print('pts before if statements', pts[0])语句会引发IndexError异常pts,这会绕过循环体的整个其余部分,因此会导致完全不同的结果。


查看完整回答
反对 回复 2022-07-26
  • 1 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信