[英]Performing an operation once in multiple iterations of a loop in Python
我正在編寫的代碼在屏幕上顯示一個形狀,並允許通過向上/向下箭頭鍵來操縱該形狀。 我一直試圖做到的是使形狀改變的數量取決於按鍵的順序。 只要輸入的內容與初始按鍵相同,形狀變化的量就會很大。 但是,當第一次“反轉”按鍵時(例如進行微調),在該點之后的每次按鍵(無論是否與初始按鍵相同)都應以較小的比例改變圓(不是交互式的,只有0.1cm的變化而不是2cm)。 該代碼已用Psychopy編寫。
我想我還沒有掌握應該為此設置循環的方式,但是我看不到如何更改循環以執行我想要的操作。 對於實際代碼的道歉,而不是最小的示例-非常感謝任何建議。
for thisTrial in trials:
endKey = 0
nKeypress = 0
count = 0
counting = 0
if thisTrial == 'ellipse':
ellipseHeightinit = 7.6,1.9 + (round(numpy.random.uniform(-1,1),1))
elif thisTrial == 'circle':
ellipseHeightinit = 7.6,7.6 + (round(numpy.random.uniform(-1,1),1))
ellipseHeight = ellipseHeightinit
ellipseStim.setSize(ellipseHeight, log = False) # set the initial size of the shape
while endKey == 0:
ellipseStim.setAutoDraw(True)
win.flip() # flip the window to see the stimuli
allKeys = event.waitKeys()
if count < 1: #store the first keypress made
for thisKey in allKeys:
firstKeypress = thisKey
count += 1
event.clearEvents()
for thisKey in allKeys: # change the size of the shape depending on key pressed
if thisKey == 'up':
nKeypress = nKeypress + 1
elif thisKey == 'down':
nKeypress = nKeypress - 1
elif thisKey == 'space':
endKey = 1
while counting < 1: # attempt to make step size large until reversal
if thisKey == firstKeypress:
ellipseHeight = 7.6, ellipseHeightinit[1] + nKeypress*20
break
elif thisKey != firstKeypress:
ellipseHeight = 7.6, ellipseHeightinit[1] + nKeypress*0.1
counting += 1
break
ellipseStim.setSize(ellipseHeight, log = False) # set new shape size
ellipseStim.setAutoDraw(False)
您應該將某個位置存儲為最后一次按下的鍵,這是最后一次使用的移動量。 如果按下的新鍵相同,則可以增加金額。 否則,將其設置為最小值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.