相关疑难解决方法(0)

为什么我的递归python函数返回None?

我有这段自称的代码:

def get_input():
    my_var = input('Enter "a" or "b": ')

    if my_var != "a" and my_var != "b":
        print('You didn\'t type "a" or "b". Try again.')
        get_input()
    else:
        return my_var

print('got input:', get_input())
Run Code Online (Sandbox Code Playgroud)

现在,如果我输入"a"或"b",一切都很好.输出是:

Type "a" or "b": a
got input: a
Run Code Online (Sandbox Code Playgroud)

但是,如果我输入其他内容然后输入"a"或"b",我会得到:

Type "a" or "b": purple
You didn't type "a" or "b". Try again.
Type "a" or "b": a
got input: None
Run Code Online (Sandbox Code Playgroud)

我不知道为什么get_input()要回来None,因为它应该只返回my_var.print语句显示None正确的值,但函数由于某种原因不返回该值.

python recursion return function

46
推荐指数
2
解决办法
7万
查看次数

Python:函数始终返回None

我有一些基本上看起来像这样的Python代码:

my_start_list = ...

def process ( my_list ):
    #do some stuff

    if len(my_list) > 1:
        process(my_list)
    else:
        print(my_list)
        return my_list

print(process(my_start_list))
Run Code Online (Sandbox Code Playgroud)

奇怪的是:print(my_list)打印出正确的内容.但是,打印函数返回值的第二个print语句始终打印"None".即使我用return("abc")替换正常的return语句,它仍然是None.

由于变量的内容在return语句之前似乎是正确的一行,我不知道从哪里开始调试.是否有可能导致此问题的常见问题?

python return

9
推荐指数
2
解决办法
1万
查看次数

为什么此生成器(使用递归)无法产生直观的结果

我编写了一个简单的生成器函数,该函数接受一个可能包含子列表的列表,并尝试展平该列表:

因此[1,[2,3],4,[5,[6,7],8]]应产生1,2,3,4,5,6,7,8

如果我只想打印出值(而不是生成器),它看起来像这样,这可行:

#  Code A
def flatten_list_of_lists(my_list):
    for element in my_list:
        if isinstance(element, list):
            flatten_list_of_lists(element)
        else:
            print(element)

my_list = [1, [2, 3], 4, [5, [6, 7], 8]]
flatten_list_of_lists(my_list)
Run Code Online (Sandbox Code Playgroud)

并按预期打印出1,2,3,4,5,6,7,8

但是,当我将代码更改为此:

#  Code B
def flatten_list_of_lists(my_list):
    for element in my_list:
        if isinstance(element, list):
            flatten_list_of_lists(element)
        else:
            yield element

for i in flatten_list_of_lists(my_list):
    print(i)
Run Code Online (Sandbox Code Playgroud)

只是将打印转换为成品,程序仅打印出1,4。

我将在下面粘贴有效的代码。但是我想知道为什么以前的代码不起作用?如果代码A正确地“打印”了数字,为什么代码B不能正确地“屈服”数字呢?

似乎我对生成器如何使用递归有基本的误解。

该代码实际上有效:

#  Code C
def flatten_list_of_lists_v2(my_list):
    for element in my_list:
        if isinstance(element, list):
            for sub_element in flatten_list_of_lists_v2(element):
                yield sub_element
        else:
            yield element

l = [] …
Run Code Online (Sandbox Code Playgroud)

python recursion generator

0
推荐指数
1
解决办法
40
查看次数

标签 统计

python ×3

recursion ×2

return ×2

function ×1

generator ×1