Skip to main content
 首页 » 编程设计

python之如何根据 Python 中的另一个集合对集合进行排序

2024年08月23日35kerrycode

我是 Python 的新手,我需要帮助解决以下问题。我在下面发布的这个定义将采用表示矩形 Ex 的元组集合。 (宽度,高度)。

在该方法中,我首先对矩形集合进行排序,使宽度最大的元素位于列表的开头,然后我稍后使用该集合为每个矩形分配 UPPER_LEFT_X 和 UPPER_LEFT_Y 坐标。

我的问题是,我如何获取这个坐标集合并按照与 original_rectangle_collection 完全相同的顺序对其进行排序? Driver 的工作方式是确定的坐标必须按照与原始矩形集合相同的顺序给出。谢谢!让我知道是否需要更多解释。

def find_best_coordinates(rectangles): 
    placement = [] 
    upper_left_x = 0 
    upper_left_y = 0 
    loop_count = 0 
 
    original_rectangle_collection = rectangles 
    #sort the rectangles according to width. 
    rectangles.sort(key=operator.itemgetter(0)) 
    #reverse the list so the tallest rectanlgle is placed first 
    rectangles.reverse() 
 
 
    #set the max width to the tallest rectangle's width 
    max_width = rectangles[0][0] 
    #print("Max width",max_width) 
 
    #loop through and place the rectangles 
    for rectangle in rectangles: 
        if loop_count == 0: 
            max_width = rectangle[0] 
        height = rectangle[1] 
        coordinate = (upper_left_x, upper_left_y)   
        placement.insert(0, coordinate)              
        upper_left_y = upper_left_y - height - 990 
        loop_count = loop_count + 1 
        if loop_count == 50: 
            upper_left_x = upper_left_x + max_width + 990 
           # print("x = ", upper_left_x) 
            loop_count = 0 
            #print("y = ", upper_left_y) 
            upper_left_y = 0 
 
    #reverse the list before it gets returned 
    placement.reverse()                             
    return placement 

请您参考如下方法:

您可以这样做,始终将原始索引与矩形一起传递,并将其与生成的坐标保持一致。

# Store indexes 
rdicts = [{'index': i, 'rectangle': r} for i, r in enumerate(rectangles)] 
# Sort by width 
rdicts.sort(key=lambda d: d['rectangle'][0], reverse=True) 
 
placement = [] 
for rdict in rdicts: 
    rectangle = rdict['rectangle'] 
    ... # do the rest of your algorithm 
    # Add the calculated coordinate, along with the original index 
    placement.append({'index': rdict['index'], 'coordinate': coordinate}) 
 
# Sort by the original index 
placement.sort(key=lambda p: p['index']) 
# Return the coordinates without the indexes. 
ordered_placement = [p['coordinate'] for p in placement]