首页 > 解决方案 > 查找半径外的坐标

问题描述

我是 Python 的初学者。我需要获取半径之外的箭头(点)的数量。我知道答案是什么,但是如何在 Python 中获得该输出?

这就是我所拥有的:

points = [(4, 5), (-0, 2), (4, 7), (1, -3), (3, -2), (4, 5), (3, 2), (5, 7), (-5, 7), (2, 2), (-4, 5), (0, -2),(-4, 7), (-1, 3), (-3, 2), (-4, -5), (-3, 2), (5, 7), (5, 7), (2, 2), (9, 9), (-8, -9)]
center = (0,0)
radius = 9

标签: python-3.x

解决方案


您可以使用列表理解

import math

points = [(4, 5), (-0, 2), (4, 7), (1, -3), (3, -2), (4, 5), (3, 2), (5, 7),
          (-5, 7), (2, 2), (-4, 5), (0, -2), (-4, 7), (-1, 3), (-3, 2), (-4, -5),
          (-3, 2), (5, 7), (5, 7), (2, 2), (9, 9), (-8, -9)]
center = (0, 0)
radius = 9

points_outside_radius = [
    p 
    for p in points 
    if math.sqrt((p[0] - center[0]) ** 2 + (p[1] - center[1]) ** 2) > radius
]
num_points_outside_radius = len(points_outside_radius)
print(f'There are {num_points_outside_radius} points outside the radius:')
print(points_outside_radius)

输出:

There are 2 points outside the radius:
[(9, 9), (-8, -9)]

请注意,如果您需要将中心更改为原点以外的其他值,我使用了完整的欧几里得距离公式。


推荐阅读