首页 > 解决方案 > 使用 Python 测试回文时输出不正确

问题描述

我正在编写一个程序来使用 Python 识别回文,使用列表。但是,我的程序总是声明输入单词是回文,即使它显然不是


word = input("Type a word, and I'll tell you if it's a palidrome or not: ")
word = " ".join(word)

new_word = word.split() #forms a list from user-inputted word
print(new_word)

variable = new_word
variable.reverse() #reverses word list 
print(variable)

if variable == new_word:
    print("This is a palidrome")
else:
    print("This is not a palidrome")

标签: python

解决方案


始终正确的原因variable == new_word是,在这种情况下,赋值运算符只是创建了一个新指针,而不是一个新列表。

换句话说,variable = new_word不复制列表——它指向内存中的同一个列表variable因此,当您 reverse 时variable,您实际上是在反转原始列表。如果您在运行new_word variable.reverse()打印,您可以看到这一点。

这篇文章是对指针的有用介绍,这篇文章很好地解释了赋值、浅拷贝和深拷贝。由于您的列表只是一个字符串列表,因此浅拷贝可以解决问题。 [1] 深拷贝是矫枉过正,但它也有效。

浅拷贝:

variable = list(new_word)

对于 Python 3.3 及更高版本,列表具有内置copy方法:

variable = new_word.copy()

另一种选择是使用切片,但不提供开始或结束索引:

variable = new_word[:]

最后,该copy模块提供了一个创建浅拷贝的函数:

variable = copy.copy(new_word)

深拷贝:

import copy
variable = copy.deepcopy(new_word)

[1] 虽然mrtnlrsn说你做了一个浅拷贝,但这不是真的,正如链接的文章所解释的那样。


推荐阅读