简体   繁体   English

无法从递归函数返回列表

[英]Can not return a list from a recursive function

I'm having an issue returning the result of a recursive function with Python. 我在用Python返回递归函数的结果时遇到问题。

My function needs to return a list of pairs of possible comparisons between integers in a range of max list_upper_range . 我的函数需要返回最大范围为list_upper_range整数之间的可能比较对的列表。

It's important that two ints are paired only once each pair. 重要的是,两个整数每对只能配对一次。

The function behaves as expected until I print the result, having returned the result to where the function was called. 在将结果返回到调用该函数的位置之前,该函数将一直按预期运行。

def generate_comparisons_list(list_upper_range, iter_start, list_of_cases):
    if iter_start == list_upper_range:
        #print(list_of_cases) here verified condition was met
        return list_of_cases

    for i in range(iter_start+1, list_upper_range):
        this_case = [iter_start, i]
        list_of_cases.append(this_case)

    iter_start += 1
    generate_comparisons_list(list_upper_range, iter_start, list_of_cases)

list_of_cases_a_and_b = generate_comparisons_list(list_upper_range=6, iter_start=1, list_of_cases=[])

print(list_of_cases_a_and_b) #returns None

Result should be returned as 结果应返回为

[[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]]

Have I misunderstood the way Python handles lists in recursive functions? 我是否误解了Python处理递归函数中列表的方式?

python functions don't automatically return the last statement (the way ruby does), you have to do a python函数不会自动返回最后一条语句(ruby的方式),您必须执行

return generate_comparisons_list(list_upper_range, iter_start, list_of_cases)

at the end of your function. 在您的功能结束时。

Have a look here to see it working. 在这里看看它是否有效。

Your function generate_comparisons_list() is intended to return a list, but in the recursive call, the return value is discarded. 您的函数generate_comparisons_list()用于返回列表,但是在递归调用中,返回值被丢弃。 Your need to return the result 您需要返回结果

return generate_comparisons_list(list_upper_range, iter_start, list_of_cases)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM