2

我对 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]

这就是我想要的。

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

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

为什么会出现“无”?提前感谢您的任何帮助或见解。

4

1 回答 1

6

我没有研究你的代码,但我会说这是为了这一行:

return lst.append([1,1])

list.append()总是返回None

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

于 2012-05-05T07:01:49.403 回答