【问题标题】:How to feed a for loop with its own output in Python?如何在 Python 中使用自己的输出来提供 for 循环?
【发布时间】:2021-11-03 21:58:02
【问题描述】:

我有一个似乎无法实现的简单问题。我在python中有一个for循环,它遍历一个元组列表并输出一个元组列表。我想要做的就是将元组的输出列表传递给前面提到的 for 循环并继续这样做很多次(我决定这样做)。

所以,我在种群中有一组个体,称为 gen1。它看起来像这样:

Generation 1 population is [(214, 66, 229, 87, 259), (256, 11, 249, 75, 242), (247, 41, 206, 4, 194), (214, 61, 172, 59, 225), (270, 78, 238, 69, 261), (235, 22, 175, 31, 213), (272, 37, 222, 80, 222), (233, 70, 207, 33, 218), (227, 38, 244, 47, 229), (264, 76, 246, 52, 239), (273, 2, 201, 10, 273), (215, 85, 205, 4, 199), (268, 9, 235, 51, 195), (236, 53, 198, 43, 273), (224, 27, 212, 29, 236), (275, 64, 190, 62, 257), (226, 23, 178, 44, 202), (219, 19, 196, 8, 227), (227, 60, 238, 15, 213), (216, 62, 185, 73, 192)]

现在,我写了一个for循环如下:

for Po in gen1:
    *do some operation, including crossover*
     Ouptput gen2

我相信这类似于 python 中的递归函数,但我不想编写一个函数,我只想用它自己的输出多次更新 for 循环。如何做到这一点?

【问题讨论】:

标签: python python-3.x recursion genetic-algorithm


【解决方案1】:

我的意思是你可以在它周围包裹一个 for 循环:

n = ... # insert the number of generations
for i in range(n):
    print(f"generation {i}:")
    for Po in current_generation:
        *do some operation, including crossover*
        

因此,在循环当前生成之后是更新的生成(因为您已经更新了该数组中的值)。不过,如果您不确定代数,您也可以使用 while True: 循环和 break,一旦您达到某个阈值或您打算如何处理?

【讨论】:

  • 与其使用混淆的while True:break,不如使用while <condition>:,条件易于理解(例如,条件可以是具有明确名称的布尔变量)
【解决方案2】:

简短的回答,使用递归,它会容易得多。

def recur(param, curr_depth=0, max_recur=20):
    if(curr_depth >= max_recur or curr_depth > 900): ## Max Depth
       return param

   else:
       ## Do something
       pass
       ## print Output
       pass
       return recur(param, curr_depth + 1, max_recur)

否则,如果您绝对需要它不使用递归,则使用 while 循环而不是 for,因为 for 循环在执行过程中无法更改。

def fun(initial, max_depth=20):

   finished = False

   generation = initial

   depth = 0

   while(not finished):

       for f in generation:
           pass

       # Assign the new result
       generation = []

       if(depth > max_depth or True): ## some condition indicating you are done
           finished = True

【讨论】:

    猜你喜欢
    • 2017-06-07
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多