我是Python的新手,我需要以下问题的帮助。我在下面发布的此定义将采用表示矩形Ex的元组的集合。(宽度,高度)。
在该方法中,我首先对矩形集合进行排序,以使宽度最大的元素位于列表的开头,然后再使用此集合为每个矩形分配UPPER_LEFT_X和UPPER_LEFT_Y坐标。
我的问题是,如何获取此坐标集合并以与original_rectangle_collection完全相同的顺序对其进行排序?驱动程序的工作方式是,必须以与原始矩形集合相同的顺序给出确定的坐标。谢谢!让我知道是否需要更多说明。
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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句