猿问

如何遍历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)):
        ...
        

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

心有法竹
浏览 503回答 3
3回答

慕田峪7331174

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 前面两个圆都去掉?圆心一定是整数吗?

Cats萌萌

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)
随时随地看视频慕课网APP

相关分类

Python
我要回答