python while 和 if 有成对的条件

python while and if with pairs of conditions

我不明白为什么这不起作用,我查看了 "if any([])" 语法的使用方式,但在我的情况下,我有成对出现的条件。

我正在尝试生成一个随机的箭头序列,其中允许所有组合,但最后一个箭头的否定除外(因此,如果第一个箭头是 L,那么下一个箭头不能是 R)。如果出现不允许的序列并因此在 while 循环中,代码应该保持 Ch2 = 0,否则它应该设置 Ch2 = 1 然后我可以编写代码以移动到序列中的下一个箭头。

此外,我确信有更好的方法可以做到这一点,但我只是在学习 Python。

Arrow_Array = ['L.png', 'R.png', 'U.png', 'D.png']
Ch2 = 0

Choice1 = random.choice(Arrow_Array)

while Ch2 != 1:
Choice2 = random.choice(Arrow_Array)
if any([Choice1 == 'L.png' and Choice2 == 'R.png', Choice1 == 'R.png' and Choice2 == 'L.png', Choice1 == 'U.png' and Choice2 == 'D.png', Choice1 == 'D.png' and Choice2 == 'U.png']):

    Ch2 = 0
else:
    Ch2 = 1

如果我明白你想要什么,这个函数就做你想要的,我想:

import random

def get_arrow_seq(n):
    """
    Return a list of arrow filenames in random order, apart from the
    the restriction that arrows in opposite directions must not be
    adjacent to each other.

    """ 
    arrow_array = ['L.png', 'R.png', 'U.png', 'D.png']
    # Indexes of the arrows reversed wrt those indexed at [0,1,2,3]
    other_directions = [1,0,3,2]
    # Start off with a random direction
    last_arrow = random.choice(range(4))
    arrows = [arrow_array[last_arrow]]

    this_arrow = other_directions[last_arrow]
    for i in range(n):
        while True:
            # Keep on picking a random arrow until we find one which
            # doesn't point in the opposite direction to the last one.
            this_arrow = random.choice(range(4))
            if this_arrow != other_directions[last_arrow]:
                break
        arrows.append(arrow_array[this_arrow])
        last_arrow = this_arrow

    return arrows

print(get_arrow_seq(10))

例如:

['R.png', 'U.png', 'R.png', 'D.png', 'D.png', 'L.png', 'L.png',
 'D.png', 'D.png', 'D.png', 'L.png']

也就是说,在您的箭头图像名称数组中选择一个随机整数索引,并根据反向箭头的索引列表检查它,拒绝任何匹配项。我已经 PEP8 化了变量名等,因为我只是不习惯大写字母。