【问题标题】:Python - Create List from Recursive LoopPython - 从递归循环创建列表
【发布时间】:2015-11-04 22:09:49
【问题描述】:

我正在尝试从我的递归循环中创建一个列表。我知道它能够产生我需要的结果,因为我已经通过打印结果进行了检查。

这是我的递归循环:

def move_forward_occurences(occurrences, firstListDt):
    listingResults = []
    for x in range(0, occurrences):
        firstListDt = firstListDt + relativedelta(bdays=+2)
        listingResults.extend(firstListDt)
        return listingResults

或者,问题可能是我没有正确检查:

if occurrences != 0:
    listingResult = move_forward_occurences(occurrences, firstListDt)
    for result in listingResult:
        print(result)

如果需要的话,解释一下参数(它们已经很容易解释了): 发生次数 = 产生结果的次数 firstListDt = 开始日期

提前致谢!

【问题讨论】:

  • 循环...不是递归的...
  • " 我知道它能够产生我需要的结果,因为我已经通过打印结果进行了检查。"那么,有什么问题呢?

标签: python list loops for-loop recursion


【解决方案1】:

您的return 缩进过多。您想将返回推迟到 for 循环完成后:

def move_forward_occurences(occurrences, firstListDt):
    listingResults = []
    for x in range(0, occurrences):
        firstListDt = firstListDt + relativedelta(bdays=+2)
        listingResults.extend(firstListDt)
    return listingResults

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多