“int”对象不可编写脚本

问题描述 投票:0回答:1

我正在尝试编写一些涉及区间树的Python代码

from intervaltree import Interval, IntervalTree

def find_non_overlapping_rectangles_interval_tree(rectangles_list):

non_overlapping_rectangles = []

# Create an IntervalTree for efficient range queries
interval_tree = IntervalTree()

# Insert intervals (rectangles) into the IntervalTree
for index, rect_params in enumerate(rectangles_list):
    # Each rectangle is represented as an interval along the x-axis
    interval = Interval(rect_params[1], rect_params[3], index)
    interval_tree.add(interval)

# Iterate through each rectangle and check for overlap using the IntervalTree
for index, rect_params in enumerate(rectangles_list):
    # Query the IntervalTree for overlapping intervals along the x-axis
    overlapping_intervals = list(interval_tree.overlap(rect_params[1], rect_params[3]))

    # Check for actual overlap with these rectangles based on y-coordinates
    is_overlapping = any(
        rect_params[2] < interval.data[2] and rect_params[4] > interval.data[4]
        for interval in overlapping_intervals
    )

# If no overlap is found, add the rectangle to the non-overlapping list
if not is_overlapping:
    non_overlapping_rectangles.append(rect_params[0])    
    
return non_overlapping_rectangles

但是我经常遇到如下错误

<ipython-input-48-a2b53835e5eb> in <genexpr>(.0)
     22     # Print the data attribute of the first overlapping interval for inspection
     23         is_overlapping = any(
---> 24             rect_params[2] < interval.data[4] and rect_params[4] > interval.data[2]
     25             for interval in overlapping_intervals
     26         )

TypeError: 'int' object is not subscriptable

这个问题基本上是一个涉及矩形操作和操作的问题,建议使用区间树作为提高性能和花费更少时间的一种方法

python google-colaboratory typeerror interval-tree
1个回答
0
投票

interval.data
Interval
的第三个参数。你通过了
index
,这是一个
int
。我怀疑你是想通过
rect_params

这可能是您想要的代码:

for rect_params in rectangles_list:
    # Each rectangle is represented as an interval along the x-axis
    interval = Interval(rect_params[1], rect_params[3], rect_params)
    interval_tree.add(interval)

# Iterate through each rectangle and check for overlap using the IntervalTree
for index, rect_params in enumerate(rectangles_list):
    # Query the IntervalTree for overlapping intervals along the x-axis
    # you probably don't need to create a list, you can just use the return value
    overlapping_intervals = list(interval_tree.overlap(rect_params[1], rect_params[3]))

    # Check for actual overlap with these rectangles based on y-coordinates
    is_overlapping = any(
        rect_params[2] < interval.data[2] and rect_params[4] > interval.data[4]
        # check indices: rectangles should not overlap with themselves
        for other_index, interval in enumerate(overlapping_intervals)
        if index != other_index
    )

如果你修复了缩进,这可能会起作用。不过,很难肯定地说,因为您的问题不包含可重现的示例。

© www.soinside.com 2019 - 2024. All rights reserved.