Python代码出现无效语法错误,请求排查问题原因
Python无效语法错误修正
错误原因
Python中逻辑非的运算符是not,而非!(!是C、Java等其他编程语言的写法),这是导致你代码出现无效语法错误的直接原因。
修正后的代码
res = (True in (not (((point[0] > (p[0] - 5)) and (point[0] < (p[0] + 5))) and ((point[1] > (p[1] - 5)) and (point[1] < (p[1] + 5)))) for p in pointsClicked))
代码可读性优化
原代码嵌套层级过多,可读性较差,可重构为更清晰的写法。另外,any()函数能更直观地表达你要实现的逻辑(检查是否存在某个p,使得point不在p的5单位范围内):
def is_point_near(point, target_point): x_within = (target_point[0] - 5) < point[0] < (target_point[0] + 5) y_within = (target_point[1] - 5) < point[1] < (target_point[1] + 5) return x_within and y_within res = any(not is_point_near(point, p) for p in pointsClicked)
内容的提问来源于stack exchange,提问作者Wyatt Knepp
相关产品推荐
相关产品推荐

