【问题标题】:"For" loop Python code - does this look right/acceptable?“For”循环 Python 代码 - 这看起来正确/可接受吗?
【发布时间】:2017-07-08 20:22:56
【问题描述】:

我想创建一个“for”循环(在 Python 2 中)。我有一个障碍物列表,对于每个障碍物,如果它们是真的(即存在并出现在列表中),我想将它们附加到一个名为“tests”的列表中并调用一个名为“obstacle_detection”的函数(它处理什么当检测到障碍物时发生)(我稍后使用“测试”)。这是一个更大的程序的一部分,我不能完全确定它是否有效,所以我想知道是否有人能告诉我它是否有意义?或者告诉我一个更好的方法可能会这样做?

obstacles = [obstacle, obstacle1, obstacle2]
tests = []

counter = 0

for obstacle in obstacles:
    tests.append(0)
    tests[counter] = obstacle_detection(obstacle, pos)
    counter = counter + 1

【问题讨论】:

  • 您可以通过使用另一个 for 循环打印出数组的内容来轻松测试它是否正常工作。
  • 你见过codereview.stackexchange.com 吗?它可能更适合这个问题。
  • @JacobKrall 啊谢谢,我不知道这个!
  • @Anna.H 您想在tests 列表中附加Truecounter 值吗?您一直在附加 0:tests.append(0)
  • 使用enumerate,将缩短您的代码。

标签: python loops for-loop


【解决方案1】:

您的代码可能有意义,具体取决于您如何定义obstaclesobstacle_detection

事实上,您可以这样编写代码:

tests = [obstacle_detection(obstacle, pos) for obstacle in obstacles]

它会自动创建一个新列表,长度与obstacles 相同,并为每个obstacle 填充obstacle_detection 值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 2014-06-08
    • 2014-04-12
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多