我正在用 Python 编写一个简单的算法来打印给定元素列表的所有排列,但遇到了一个我无法调试的错误:
def perm(prefix, rest):
if len(rest) == 0:
print prefix
print len(rest)
for i in range(len(rest)):
#The next 3 prints are for debugging purposes only
print type(prefix)
print "prefix=", prefix
print "rest=", rest
newprefix = prefix.append( rest[i])
newrest = rest
newrest.pop(i)
perm(newprefix, newrest)
perm([], ['a','b','c'])
出于某种原因,我的变量“prefix”在 for 循环的第一次迭代后更改为 None 类型。这是我得到的输出:
3
<type 'list'>
prefix= []
rest= ['a', 'b', 'c']
2
<type 'NoneType'>
prefix= None
rest= ['b', 'c']
Traceback (most recent call last):
File "self2.py", line 19, in <module>
perm([], ['a','b','c'])
File "self2.py", line 16, in perm
perm(newprefix, newrest)
File "self2.py", line 13, in perm
newprefix = prefix.append( rest[i])
AttributeError: 'NoneType' object has no attribute 'append'
最佳答案
list.append
就地更改列表并返回 None
。所以在这一步之后 newprefix
实际上是 None
。
newprefix = prefix.append( rest[i])
关于Python 变量在第一次迭代后丢失类型信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16270144/