我是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
答案 0 :(得分:2)
你可以这样做,总是将原始索引与矩形一起传递,并将其与生成的坐标保持一致。
# 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]
答案 1 :(得分:1)
只需对索引进行排序,您就可以更快一些:
processing_order = sorted(
range(len(rectangles)),
key=lambda i: rectangles[i][0]
)
for rect_i in processing_order:
r = rectangles[rect_i]
# ... blah blah with r as current rectangle
# Done processing, output them in original order:
for r in rectangles:
# Still in order!