【问题标题】:How to execute code once when reaching a value and continue looping until next value is reached?如何在达到一个值时执行一次代码并继续循环直到达到下一个值?
【发布时间】:2020-10-21 08:23:58
【问题描述】:

我有一个浮动列表 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.
    """

到目前为止,正如预期的那样,每次传递我的列表值时,每帧的打印量都会增加。

【问题讨论】:

  • 你能编辑你的问题并把示例输入和预期输出放在那里吗?

标签: python python-3.x list loops


【解决方案1】:

如果您有多个要停止的值,请查看以下内容:

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]]

【讨论】:

  • 做得很好!谢谢:)
  • 很高兴能为您提供帮助。请不要忘记将答案标记为已接受并投票赞成那些对您的案件有帮助的答案
【解决方案2】:

试试

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多