【问题标题】:How to iterate Python list and delete similar element?如何迭代 Python 列表并删除相似的元素?
【发布时间】:2019-05-02 05:43:28
【问题描述】:

我有一个字典列表,代表圆的中心和半径。

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

我想根据 x 轴的位置删除封闭的圆圈。如果两个圆的x轴之差大于0小于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)):
            ...

我对 Python 很陌生,不知道如何完成它。

添加

这是我希望得到的结果:

[{centre:(743,1105), radius: 41},
 {centre:(900, 1442), radius: 40}]

每个元素都会被比较。例如:

0 41,因此将删除第二个。

|743 - 899| >= 3, |743 - 900 | >= 3,这里什么都不会发生。

0 40,因此将删除第三个。

更新

这是我想出的解决方案。但这很慢。谁知道怎么优化?

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

def removeaAdjacentCircle(circleDetails):
    circleDetails.sort(key=takeXAxis)
    newCircleDetails = []
    indexOfRemovedCircle = []
    for i in range(0, len(circleDetails)):
        if i in indexOfRemovedCircle:
            continue
        for j in range(i + 1, len(circleDetails)):
            delta = abs(circleDetails[i]['centre'][0] - circleDetails[j]['centre'][0])
            if 0 <= delta <= 3:
                if circleDetails[i]['radius'] - circleDetails[j]['radius'] >= 0:
                    indexOfRemovedCircle.append(i)
                else:
                    indexOfRemovedCircle.append(j)

    for i in range(0, len(circleDetails)):
        if i in indexOfRemovedCircle:
            continue
        newCircleDetails.append(circleDetails[i])

    return newCircleDetails

【问题讨论】:

  • difference of x axis of two circles is greater or less than 3 ,这个条件会覆盖所有的记录。你确定这是正确的吗?最后,您将只剩下 1 记录。
  • @MayankPorwal 结果将是 [{centre:(743,1105), radius: 41}, {centre:(900, 1442), radius: 40}]。第一个圆有相同的 x作为第二个。 0
  • 所以您不想再次将列表中的每个元素与每个元素进行比较?看起来你想按顺序排列它们?
  • @NimeshkaSrimal 我希望对它们中的每一个进行比较。我正在考虑使用双循环,但我不知道如何编写它。
  • 您确定您的预期输出吗?因为你的问题中有矛盾的陈述。

标签: python arrays list iteration


【解决方案1】:

使用itertools.combinations()。我相信它比嵌套循环更有效。

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

我已经把 cmets 说清楚了。如果您需要了解任何信息,请随时询问。

希望它会有所帮助:)

【讨论】:

    猜你喜欢
    • 2017-12-13
    • 1970-01-01
    • 2013-01-29
    • 2018-07-18
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2013-01-23
    相关资源
    最近更新 更多