python - 这个将“字符串”视为“列表”的回文代码如何工作?
问题描述
我发现了一个很棒的回文代码,我可以抽象地理解,但我不确定它是如何工作的。
def palindrome(word):
return word == word[::-1]
我认为单词的数据类型是“字符串”而不是“列表”。但在该代码中,它将 word 视为列表类型。它会自动更改word
为list(word)
吗?
解决方案
Python 切片表示法非常简单。取自另一个答案:
a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole array
a[start:stop:step] # start through not past stop, by step
举个例子:
word = 'abcd'
assert word[0] == 'a'
assert word[0:3] == 'abc'
assert word[0:4] == 'abcd'
assert word[0:4:2] == 'ac'
在你的情况下,如果 step 是-1
那么它会倒退:
assert word[::-1] = 'dcba'
因此,如果一个单词 back 等于单词本身,那么它是回文:
if word == word[::-1]:
return True
推荐阅读
- hibernate - 我在 OneToMany 关系中遇到错误?
- html - 在 position:fixed 之后,另一个容器占用 100% 的浏览器而不是可用空间
- assembly - 强制 clang 发出 pmull2/umull2 操作码变体
- sed - sed 更改字符串分隔符
- python - VS Code 中 Anaconda 配置和调试 python
- git - 在 GitHub CLI 中切换用户
- spring-boot - 无法在使用 jpa 的 Spring Boot 中的请求之间提交事务
- python - 使用二维 NxM 数组作为对角线创建 4 维 NxNxMxM 数组
- spring-boot - 使 Zipkin(或任何开放式跟踪框架)与现有的“跟踪 id”一起工作
- xml - 如何将 xml 作为请求正文传递并在 amazone api 网关中获取 xml 作为响应正文以进行 post 方法