如何遍历python list,然后删除近似元素

我有一个list,list里面的element是dict。
[{centre:(743,1105), radius: 41},
{centre:(743, 1106), radius: 48},
{centre:(899, 1443), radius: 48},
{centre:(900, 1442), radius: 40}]

这个关于圆心和半径的一个数据结构。我想把圆心相近的圆(横坐标相差+3/-3 左右)去掉一个(保留半径较小的)

def takeXAxis(input):
    return input['centre'][0]


def sortCircles(circleDetails):
    circleDetails.sort(key=takeXAxis)


def removeClosedCircle(circleDetails):
    newCircleDetails = []
    for i in range(len(circleDetails)):
        j = i + 1
        for j in range(len(circleDetails)):
        ...
        

接下来我就不太会了,有人能帮我看下吗?

阅读 3.9k
3 个回答
import itertools

my_list = [
    {'centre':(743,1105), 'radius': 41},
    {'centre':(743, 1106), 'radius': 48},
    {'centre':(899, 1443), 'radius': 48},
    {'centre':(900, 1442), 'radius': 40}
]

for a, b in itertools.combinations(my_list, 2):

    # only need to do something if the diff is in range..
    if abs(a['centre'][0] - b['centre'][0]) <= 3:

        # check the radius, if bigger, remove it, else remove the other.
        if a['radius'] > b['radius']:
            my_list.remove(a)
        else:
            my_list.remove(b)

print my_list

问题不清楚, 如果有圆 x=1, 另一个 x=5 这时来一个x=3 前面两个圆都去掉?
圆心一定是整数吗?

li = [{'centre': (743, 1105), 'radius': 41},
      {'centre': (743, 1106), 'radius': 48},
      {'centre': (899, 1443), 'radius': 48},
      {'centre': (900, 1442), 'radius': 40}]

li_radius = sorted(li, key=lambda x: x['radius'])  # 根据radius排序
li_centre = sorted(li_radius, key=lambda x: x['centre'][0])  # 再根据圆心横坐标排序

li_index = [i for i in range(1, len(li_centre)) if
            (li_centre[i]['centre'][0] - li_centre[i - 1]['centre'][0]) <= 3]  # 要删除元素的索引号
result = [li_centre[i] for i in range(len(li_centre)) if (i not in li_index)]  # 根据索引号删除列表相关元素
print(result)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题