python while和if带有成对条件

python while和if带有成对条件,python,if-statement,while-loop,Python,If Statement,While Loop,我不明白为什么这不起作用,我已经研究了“if any([])”语法是如何使用的,但在我的例子中,我有成对的条件 我试图生成一个随机的箭头序列,其中所有的组合都是允许的,除了最后一个箭头的否定(因此,如果第一个箭头是L,那么下一个箭头就不能是R)。如果出现不允许的序列,那么代码应该保持Ch2=0,因此在while循环中,否则它应该设置Ch2=1,然后我可以编写代码以转到序列中的下一个箭头 另外,我确信有更好的方法可以做到这一点,但我只是在学习Python Arrow_Array = ['L.png

我不明白为什么这不起作用,我已经研究了“if any([])”语法是如何使用的,但在我的例子中,我有成对的条件

我试图生成一个随机的箭头序列,其中所有的组合都是允许的,除了最后一个箭头的否定(因此,如果第一个箭头是L,那么下一个箭头就不能是R)。如果出现不允许的序列,那么代码应该保持Ch2=0,因此在while循环中,否则它应该设置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']

也就是说,在箭头图像名称数组中选择一个随机整数索引,并对照反向箭头的索引列表进行检查,拒绝任何匹配项。我已经对变量名等进行了修改,因为我不习惯大写。

请定义不起作用。您的错误是什么?代码没有正确缩进?在while语句之后缩进代码。代码仍然生成无效序列-因此,如果第一个箭头是“L”,我仍然会得到第二个箭头是“R”的场景,这是不应该发生的。缩进没有解决问题,但感谢您对格式的帮助,这还是新鲜事!