python - 为什么打印结果与功能不同

标签 python

这是我的 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/

相关文章:

python - 将重复的行标签转换为 Pandas 中的列标题

python - SQLAlchemy 查询具有关系计数的对象

python - OpenShift、python 2.7 和带 htaccess 的静态文件

python - Windows - 无法通过 pip 安装 pyautogui - 错误 : Command "python setup.py egg_info" failed with error code 1

Python 日期时间类型错误,需要整数

python - Swift REPL 抛出 python 错误?

python - 在循环中一次从列表中检索 2 个项目?

python - 我应该将参数作为继承对象吗?

python - 检查序列是否包含非连续子序列的最快方法?

Python - 分割整个文本文件