我对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])
Run Code Online (Sandbox Code Playgroud)
返回:
>>>
[1]
[1, 1]
[1, 1, 1]
Run Code Online (Sandbox Code Playgroud)
这就是我想要的.
我认为在函数内部的列表中使用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])
Run Code Online (Sandbox Code Playgroud)
但这回归:
>>>
[1]
None
None
Run Code Online (Sandbox Code Playgroud)
为什么"无"出现?提前感谢任何帮助或见解.
我没有研究你的代码,但我会说这是为了这一行:
return lst.append([1,1])
Run Code Online (Sandbox Code Playgroud)
list.append()总是回来None.
因此,lst.append([1,1])将追加[1,1]到lst并返回None.
| 归档时间: |
|
| 查看次数: |
3754 次 |
| 最近记录: |