For循环重复并生成比指定值更多的值

2024-06-02 06:50:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在画布上粘贴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)]

Tags: in图像imgfor画布rangelocationwidth
2条回答

您的else语句没有正确缩进。试试这个

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))

在第一次迭代中,将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不重叠的位置

# Instead of iterating only 3 times, try until list is full.
while len(locations_used) < n:
        
    logo_location_x, logo_location_y = logo_position(canvas_width, canvas_height, logo_width, logo_height)
    
    # Don't add position until it is checked that it doesn't overlap.
    # locations_used.append((logo_location_x, logo_location_y))

    # Check if new rectangle candidate overlaps with previous ones.
    overlap = False
    for img in locations_used:
        # Fix range usage. I hope this is what you want.
        if logo_location_x in range(img[0] - logo_width, img[0] + logo_width) and logo_location_y in range(img[1] - logo_height, img[1] + logo_height):
            overlap = True
            break
    
    # Add position to list after you ensure that new position
    if not overlap:
        locations_used.append((logo_location_x, logo_location_y))

相关问题 更多 >