繁体   English   中英

python while和if与成对条件

[英]python while and if with pairs of conditions

我不知道为什么这行不通,我已经研究了如何使用“ 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']

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM