繁体   English   中英

Python函数返回None,不清楚为什么

[英]Python function returns None, unclear why

我是python的新手,遇到了我无法解释的问题。 我尝试在此处搜索论坛答案,但是发现的情况与我的情况不符。 感觉好像我缺少一些基本的东西,但是我没有看到(显然...)

这段代码按照我期望的方式运行:

import string

mults = [1,2,3,4,6,7,9,10,12,15,16,19,21,22,24]

def factor_exp(lst):
    if lst[-1] == 1:
        lst.pop()
        return lst+[1]
    if lst[-1] == 2:
        lst.pop()
        return lst+[1,1]
    else:
        return "Should never get here"

print factor_exp([1])
print factor_exp([2])
print factor_exp([1,2])

返回:

>>> 
[1]
[1, 1]
[1, 1, 1]

这就是我想要的。

我认为在函数内的列表上使用追加和扩展也可以。 在代码底部附近添加了一个“追加”。

import string

mults = [1,2,3,4,6,7,9,10,12,15,16,19,21,22,24]

def factor_exp(lst):
    if lst[-1] == 1:
        lst.pop()
        return lst+[1]
    if lst[-1] == 2:
        lst.pop()
        return lst.append([1,1])
    else:
        return "Should never get here"


print factor_exp([1])
print factor_exp([2])
print factor_exp([1,2])

但这返回:

>>> 
[1]
None
None

为什么出现“无”? 在此先感谢您的帮助或见解。

我没有研究您的代码,但我想说的是:

return lst.append([1,1])

list.append()始终返回None

所以lst.append([1,1])会将[1,1]附加到lst并返回None

暂无
暂无

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

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