【问题标题】:How to get multiple conditionals to execute at the same time?如何让多个条件同时执行?
【发布时间】:2018-01-13 01:18:45
【问题描述】:

我决定尝试做一个海龟项目来学习随机命令。我的问题在这段代码中:

pos = 360
while a.ycor()<pos:
 a.forward(randint(1,5))
while b.ycor()<pos:
 b.forward(randint(1,5))
while c.ycor()<pos:
 c.forward(randint(1,5))
while d.ycor()<pos:
 d.forward(randint(1,5))
while e.ycor()<pos:
 e.forward(randint(1,5))

如何让所有条件同时执行以开始比赛(所有海龟同时起飞)?

【问题讨论】:

  • 如while condition1 and condition2 and condition3等?
  • 你能用上面的代码解释一下你想要什么输出吗?数着前进的步数还不够?
  • 你可能想看看这个:stackoverflow.com/questions/40050438/…
  • 你得到你想要的输出了吗?
  • 请阅读How to ask。

标签: python turtle-graphics


【解决方案1】:

我不能 100% 确定您要做什么,因此假设您希望同时运行多个功能,请使用 multiprocessing 或 threading 模块。 快速多处理示例:

import multiprocessing, time

def aFunction(aVar):
    time.sleep(5)
    print(f"Ye {aVar}")

if __name__ == '__main__':
    multiprocessing.freeze_support()

    pool = multiprocessing.Pool(4)
    pool.map(aFunction, [X for X in range(4)])
    input("Press Return to exit")

【讨论】:

    【解决方案2】:

    您可以尝试使用逻辑运算符AND:

    pos = 360
    while a.ycor()<pos and
          b.ycor()<pos and
          c.ycor()<pos and
          d.ycor()<pos and
          e.ycor()<pos:
    
         a.forward(randint(1,5))
         b.forward(randint(1,5))
         c.forward(randint(1,5))
         d.forward(randint(1,5))
         e.forward(randint(1,5))
    

    【讨论】:

      【解决方案3】:

      为避免重复,您可以将变量和方法放在字典中,然后循环遍历它们。

      pos = 360
      
      d = {a: a.ycor, b: b.ycor, c: c.ycor, d: d.ycor, e: e.ycor}
      
      for k, v in d.items():
          while v() < pos:
              k.forward(randint(1, 5))
      

      【讨论】:

        猜你喜欢
        • 2022-01-24
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多