python - 使用 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")
解决方案
始终正确的原因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说你做了一个浅拷贝,但这不是真的,正如链接的文章所解释的那样。
推荐阅读
- html - 如何在 node.js 中访问标签的 href
- c# - 如何访问具有不同架构的旧表?
- php - 对 PHP 数组进行分组并获取最大值和最大值的总和
- node.js - Puppeteer:如何在评估中提交表单后获取新页面对象?
- unix - 在文件末尾匹配后拆分文件并将匹配保留在文件 unix 中
- python-3.x - googletrans Translate() 不适用于 Spyder 但适用于 Colab
- bash - 将文件从 Hadoop 多个目录复制到边缘节点文件夹
- prometheus - 使用 PromQL 计算可用性
- java - 如何从测试中排除@EnableJpaRepositories?
- racket - 扩展归约关系