我试图在画布上粘贴3个矩形图像。目标是使图像位于画布内,并且不会重叠。为此,我决定生成3个两元组值,作为图像左上角xy坐标的位置。大概是这样的:
locations_used = [(950, 916), (1097, 119), (1290, 526)]
它所做的是重复第一个值3x,然后添加2个新值,当我指定3时,总共给出5个位置。像这样:
[(950, 916), (950, 916), (950, 916), (1097, 119), (1290, 526)]
这是我的代码的MRE:
n = 3
canvas_width = 500
canvas_height = 300
logo_width = 50
logo_height = 30
locations_used = []
for i in range(0, n):
logo_location_x, logo_location_y = logo_position(canvas_width, canvas_height, logo_width, logo_height)
locations_used.append((logo_location_x, logo_location_y))
for img in locations_used:
if logo_location_x in range(img[0], logo_width) or logo_location_y in range(img[1], logo_height):
pass
else:
while len(locations_used) < n:
locations_used.append((logo_location_x, logo_location_y))
print(len(locations_used))
print(locations_used)
print('\n')
输出:
5
[(950, 916), (950, 916), (950, 916), (1097, 119), (1290, 526)]
您的else语句没有正确缩进。试试这个
在第一次迭代中,将
logo_location_x
(950)和logo_location_y
(916)与range(950, 50)
和range(916, 30)
进行比较。由于start
参数小于stop
,所以范围为空,程序执行到else
子句。当locations_used
的长度小于3时,将添加相同的值,从而使数组[(950, 916), (950, 916), (950, 916]
在接下来的两次迭代中,每个新的
x, y
对被添加到locations_used
。虽然range(img[0], logo_width)
和range(img[1], logo_height)
仍然为空,但locations_used
的长度大于n
,因此不会添加额外的元素这是经过编辑的代码,用于创建
n
不重叠的位置相关问题 更多 >
编程相关推荐