这是我的 Python 函数:
def Ggen(word):
result = []
while(len(word)!=1):
a = word.pop()
b = word
temp = (a,b)
print temp
result.append(temp)
return result
假设我有数据调用 test = ['f','c','a','m','p']
。
我在函数中从 print
生成的结果是:
('p', ['f', 'c', 'a', 'm'])
('m', ['f', 'c', 'a'])
('a', ['f', 'c'])
('c', ['f'])
但是如果我运行 Ggen(test)
我会得到这个:
[('p', ['f']), ('m', ['f']), ('a', ['f']), ('c', ['f'])]
我的代码发生了什么。有人如何从上面得到类似的结果吗?
最佳答案
每次您 word.pop()
时,您都在更改包含在 result
中的列表的引用。因此,您正在打印中间值,但最终返回的将是退出 while 循环的 word
列表。
如果您想返回您看到的打印内容,则每次从列表中pop
时都需要复制列表。
def Ggen(word):
result = []
while(len(word)!=1):
result.append((word.pop(),word[:]))
return result
关于python - 为什么打印结果与功能不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011438/