Python 如何在达到某个值时执行一次代码,并继续循环直到达到下一个值?
我有一个浮动列表Python 如何在达到某个值时执行一次代码,并继续循环直到达到下一个值?,python,python-3.x,list,loops,Python,Python 3.x,List,Loops,我有一个浮动列表listItemPos,另外一个浮动在每帧playPosition中更新 每次playPosition超过listItemPos中的一个值时,我都试图执行一段代码 这就是我的代码的样子: listItemPos.sort() #sort the item positions # This is the loop being called each frame: for x in range(0, len(listItemPos)): if
listItemPos
,另外一个浮动在每帧playPosition
中更新
每次playPosition
超过listItemPos
中的一个值时,我都试图执行一段代码
这就是我的代码的样子:
listItemPos.sort() #sort the item positions
# This is the loop being called each frame:
for x in range(0, len(listItemPos)):
if playPosition >= listItemPos[x]:
print("I passed item number " + str(x))
"""
This is where I would like to have a function execute only once
when reaching one of the value of my list.
"""
现在,正如预期的那样,每次传递列表的值时,每帧的打印量都会增加。试试看
listItemPos.sort() #sort the item positions
target = 2 # use a target flag
for x in range(0, len(listItemPos)):
if playPosition >= listItemPos[x]:
print("I passed item number " + str(x))
if listItemPos[x] == target:
func()
target = None # remove the target
如果有多个值需要停止,请查看以下内容:
import numpy as np
listItemPos.sort() #sort the item positions
# The values you want to stop for (numpy so we can do fancy filtering)
stopvalues = np.array([4,8,32])
# This is the loop being called each frame:
for x in range(0, len(listItemPos)):
if playPosition >= listItemPos[x]:
print("I passed item number " + str(x))
if x in stopvalues:
executeFunc()
# so its executed once, remove the corresponding value:
stopvalues = stopvalues[[stopvalues != x]]
你能编辑你的问题并把输入和预期输出放在那里吗?这很好!谢谢:)很高兴我能帮你。请不要忘记将答案标记为已接受,并对那些有助于您处理案例的答案进行投票