[英]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.