我对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
为什么出现“无”?在此先感谢您的帮助或见解。