排除可能的图像位置

2024-09-25 00:21:59 发布

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

我需要放置图像,这样它们就不会在对方身上。我在看矩阵3x3,所以有9个地方。图像是水平的,有两个位置。我试过这样做(编辑):

other_position = [e for e in range(9)]

def find_horizontal_position(avaiable_pos):
    myList = avaiable_pos
    print(avaiable_pos)
    try:
        possible_position = [0,1,3,4,6,7] # positions where image is not cut in half
        position = random.choice(possible_position)
        myList.remove(position)
        myList.remove(position + 1)
    except ValueError:
        return find_horizontal_position(avaiable_pos)
    return myList, position

for _ in range(2):
    other_position, position = find_horizontal_position(other_position)
    print(position)

有时它会产生如下输出:

1
[0, 3, 4, 5, 6, 7, 8]
[0, 3, 4, 5, 6, 7, 8]
[0, 3, 4, 5, 6, 7, 8]
[0, 3, 4, 5, 6, 7, 8]
[3, 4, 5, 6, 7, 8]
4
[3, 6, 7, 8]

第一个图像被放置在位置1上,因此1和2被取出。第二张照片在4号位置,但顺便说一下,它拿走了0。。。也许有更好的方法


Tags: inpos图像forreturnpositionrangefind
1条回答
网友
1楼 · 发布于 2024-09-25 00:21:59

在EXPECT子句中,加入一个return语句:

return   find_horizontal_position(avaiable_pos)

否则,即使尝试放置图像的位置无效,仍将执行return语句

return myList, position

在你的例子中有position==0。请注意,即使存在一个有效的解决方案,您的方法也可能找不到有效的解决方案,我建议在所有对上循环

(img1leftposition, imp2leftposition), img1leftposition != imp2leftposition

其中img1leftposition和img2leftposition位于possible_position(有很多方法可以做到这一点,使用

for pair in zip(possible_position, possible_position):
    ...

相关问题 更多 >