如何检查列表中的元素是否具有重叠的数值

发布于 2025-02-10 10:40:42 字数 669 浏览 4 评论 0 原文

我正在处理某些项目具有重叠值的列表。

list=[[7, 11, 'Feature01'],
      [2, 6, 'Feature02'],
      [31, 59, 'Feature03'],
      [31, 41, 'Feature04'],
      [20, 40, 'Feature05'],
      [25, 30, 'Feature06']

例如,在以下项目中,功能04位于功能03坐标中。

[31, 59, 'Feature03'], [31, 41, 'Feature04'], 

同样,在下面的示例中,功能06位于功能05坐标中。

[20, 40, 'Feature05'], [25, 30, 'Feature06']

我想在这种重叠的情况下仅保留一个项目,并更新列表的原始/主列表以保存非重叠的列表项目。

我发现几乎相似,但无法正常工作。

I am working with a list of lists where some items have overlapping values.

list=[[7, 11, 'Feature01'],
      [2, 6, 'Feature02'],
      [31, 59, 'Feature03'],
      [31, 41, 'Feature04'],
      [20, 40, 'Feature05'],
      [25, 30, 'Feature06']

For example, in the below items Feature04 lies inside Feature03 coordinates.

[31, 59, 'Feature03'], [31, 41, 'Feature04'], 

Similarly in the below example, Feature06 lies inside Feature05 coordinates.

[20, 40, 'Feature05'], [25, 30, 'Feature06']

I want to retain only one item in such an overlapping scenario and update the original/master list of lists to save non-overlapping list items.

I found almost similar question but could not get it to work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

留一抹残留的笑 2025-02-17 10:40:42

按间隔的起点对列表进行排序,根据间隔的终点(按降序)进行抢七。然后,如果没有最近添加的间隔包含一个间隔,则添加了一个间隔:

lst.sort(key=lambda x: (x[0], -x[1]))
result = [lst[0]]

for entry in lst[1:]:
    current_start, current_end, _ = entry
    last_start, last_end, _ = result[-1]
    if not (last_start <= current_start <= current_end <= last_end):
        result.append(entry)
        
print(result)

此输出:

[[2, 6, 'Feature02'], [7, 11, 'Feature01'], [20, 40, 'Feature05'], [31, 59, 'Feature03']]

Sort the list by the starting point of the interval, tiebreaking based on endpoints of intervals (in descending order). Then, you add an interval if it isn't contained by the most recently added interval to the result:

lst.sort(key=lambda x: (x[0], -x[1]))
result = [lst[0]]

for entry in lst[1:]:
    current_start, current_end, _ = entry
    last_start, last_end, _ = result[-1]
    if not (last_start <= current_start <= current_end <= last_end):
        result.append(entry)
        
print(result)

This outputs:

[[2, 6, 'Feature02'], [7, 11, 'Feature01'], [20, 40, 'Feature05'], [31, 59, 'Feature03']]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文