【问题标题】:python how to loop functionspython如何循环函数
【发布时间】:2018-09-25 02:26:00
【问题描述】:

我的代码如下,在 Windows 操作系统上使用 spyder

import numpy 
catch_rate = 0.5 
def tenMiss(throws):
    for i in range(len(throws) - 3): # loop through the throws
        print(sum(throws[i:i+3] < catch_rate))
        if sum(throws[i:i+3] < catch_rate) == 0: # total misses out of 10 throws
            print("ten Misses!")
            return True 
        return False
throws = numpy.random.random(20)
print (tenMiss(throws))

我正在尝试使用“for”循环将此函数循环 700 次,然后添加一个计数变量以确定该函数返回 true 的次数。我遇到的麻烦是确定 wthat 变量应该进入 for 循环以“选择”这个函数来循环。一旦我到达那里,我将如何合并计数变量

【问题讨论】:

  • 函数的内部循环只执行一次。这是故意的吗?
  • 是的,它是有意只运行该函数一次。如果您认为多次运行该功能会更好,我很乐意在这里说明原因。
  • 那你为什么需要循环呢?

标签: python for-loop counter


【解决方案1】:
true_count = 0
for x in range(700):
    result = some_function()
    if result is True:
        true_count += 1
print('True was returned %d times' % true_count)

【讨论】:

  • John 感谢您的回复, some_function() 是一个变量还是它实际上是一个函数?
  • @natedowg2000 这应该是一个函数。在您的情况下,这将是您的 tenMiss() 函数,但我想提供一个可以与任何此类函数一起使用的通用解决方案。
猜你喜欢
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多